2016-10-11 2 views
0

나는이 데이터를 얻고 싶지만 혼란스럽고 어떻게해야하는지 알고 싶습니다. 다리에 접근하고 싶습니다. 다리 거리에서 텍스트. 그런 다음 단계를 수행 한 후 다시 거리를두고 텍스트를 입력하십시오. "루트"에서Json 안드로이드에서 여러 객체 가져 오기

은> "다리"== -> 거리 -> 다음

텍스트

는 단계 "루트"==> "다리"==> "단계를"운전하세요 -> 거리 -> 텍스트

처음에는 개체가 너무 커서 혼란스러운 개체가 다시 있습니다. 어떤 도움을 주시면 감사하겠습니다.

{ 
     "geocoded_waypoints" : [ 
      { 
      "geocoder_status" : "OK", 
      "place_id" : "ChIJ2QeB5YMEGTkRYiR-zGy-OsI", 
      "types" : [ "locality", "political" ] 
      }, 
      { 
      "geocoder_status" : "OK", 
      "place_id" : "ChIJ2afeeFcxOzkRL9RVTscv17o", 
      "types" : [ "locality", "political" ] 
      } 
     ], 
     "routes" : [ 
      { 
      "bounds" : { 
       "northeast" : { 
        "lat" : 31.55462439999999, 
        "lng" : 74.3571711 
       }, 
       "southwest" : { 
        "lat" : 30.1981178, 
        "lng" : 71.4687352 
       } 
      }, 
      "copyrights" : "Map data ©2016 Google", 
      "legs" : [ 
       { 
        "distance" : { 
         "text" : "348 km", 
         "value" : 347978 
        }, 
        "duration" : { 
         "text" : "4 hours 49 mins", 
         "value" : 17335 
        }, 
        "end_address" : "Multan, Pakistan", 
        "end_location" : { 
         "lat" : 30.1981178, 
         "lng" : 71.4687352 
        }, 
        "start_address" : "Lahore, Pakistan", 
        "start_location" : { 
         "lat" : 31.55462439999999, 
         "lng" : 74.3571711 
        }, 
        "steps" : [ 
         { 
         "distance" : { 
          "text" : "67 m", 
          "value" : 67 
         }, 
         "duration" : { 
          "text" : "1 min", 
          "value" : 9 
         }, 
         "end_location" : { 
          "lat" : 31.5549532, 
          "lng" : 74.3565735 
         }, 
         "html_instructions" : "Head \u003cb\u003enorthwest\u003c/b\u003e on \u003cb\u003eAllama Iqbal Rd\u003c/b\u003e", 
         "polyline" : { 
          "points" : "k_r_Ei{ydM[[email protected]@bA" 
         }, 
         "start_location" : { 
          "lat" : 31.55462439999999, 
          "lng" : 74.3571711 
         }, 
         "travel_mode" : "DRIVING" 
         }, 
+0

내가 걱정이에 대한 GSON, 아무것도를 사용하고 쉽게 당신이 원하는 경우에 나는 당신에게 예를 수) = 사용. 아니면 먼저 읽으려고합니까? –

+0

은 http://stackoverflow.com/questions/17673057/how-to-parse-this-nested-json-array-in-android를 참조하십시오. – sasikumar

답변

2

수동 방법은 JSON ([] beetwen)에게 오브젝트 (beetwen {}) 또는 어레이를 제공

한마디한다. json의 깊숙한 곳에서 sth를 얻으려면 각 단계를 거쳐야합니다. 당신은 JSON의 조각을 넣어,하지만 난 그것을 폐쇄하고 우리는 시작 JSON 객체에있는 (주 중괄호가 있기 때문에 {}) :

{ 
    "geocoded_waypoints" : [ 
     { 
     "geocoder_status" : "OK", 
     "place_id" : "ChIJ2QeB5YMEGTkRYiR-zGy-OsI", 
     "types" : [ "locality", "political" ] 
     }, 
     { 
     "geocoder_status" : "OK", 
     "place_id" : "ChIJ2afeeFcxOzkRL9RVTscv17o", 
     "types" : [ "locality", "political" ] 
     } 
    ], 
    "routes" : [ 
     { 
     "bounds" : { 
      "northeast" : { 
       "lat" : 31.55462439999999, 
       "lng" : 74.3571711 
      }, 
      "southwest" : { 
       "lat" : 30.1981178, 
       "lng" : 71.4687352 
      } 
     }, 
     "copyrights" : "Map data ©2016 Google", 
     "legs" : [ 
      { 
       "distance" : { 
        "text" : "348 km", 
        "value" : 347978 
       }, 
       "duration" : { 
        "text" : "4 hours 49 mins", 
        "value" : 17335 
       }, 
       "end_address" : "Multan, Pakistan", 
       "end_location" : { 
        "lat" : 30.1981178, 
        "lng" : 71.4687352 
       }, 
       "start_address" : "Lahore, Pakistan", 
       "start_location" : { 
        "lat" : 31.55462439999999, 
        "lng" : 74.3571711 
       }, 
       "steps" : [ 
        { 
        "distance" : { 
         "text" : "67 m", 
         "value" : 67 
        }, 
        "duration" : { 
         "text" : "1 min", 
         "value" : 9 
        }, 
        "end_location" : { 
         "lat" : 31.5549532, 
         "lng" : 74.3565735 
        }, 
        "html_instructions" : "Head \u003cb\u003enorthwest\u003c/b\u003e on \u003cb\u003eAllama Iqbal Rd\u003c/b\u003e", 
        "polyline" : { 
         "points" : "k_r_Ei{ydM[[email protected]@bA" 
        }, 
        "start_location" : { 
         "lat" : 31.55462439999999, 
         "lng" : 74.3571711 
        }, 
        "travel_mode" : "DRIVING" 
        }] 
      } 
      ] 
     } 
    ] 

}

의 당신이 jsonString "라는 문자열로이 있다고 가정 해 봅시다 ". 다음과 같이 json 객체를 만듭니다.

JSONObject jsonObject = new JSONObject(jsonString); 

json 배열 ([중괄호 사이])보다 "경로"가 필요합니다.

JSONArray routesArray = jsonObject.getJSONArray("routes"); 

는이 같은 반복 (JSON 개체가) 각 배열 요소를 통해 이동하십시오 :

for (int i = 0; i < routesArray.length(); i++) { 
    //do sth 
} 

그리고 당신은 당신의 "다리"와 같은를 얻을 당신은 당신의 주 된 JSONObject에 깊이 갈이 배열을 만들 이 :

JSONObject routeObject = routesArray.get(i); 
routeObject.get("legs"); 

위와 같이 깊고 깊게.

자동

이 GSON 라이브러리와 일부 JSON 뽀조 파서를 사용하는 것이 훨씬 쉽다.

당신은 당신의 build.gradle에 GSON을 가져옵니다

compile 'com.google.code.gson:gson:2.4' 

parser을 사용할 수 있습니다보다. 소스 유형 "JSON"및 "주석 스타일"Gson을 선택하십시오. json을 텍스트 상자에 놓고 Preview를 클릭하거나 ZIP을 다운로드하십시오. 패키지 이름과 주 클래스 이름을 넣거나 나중에 수동으로 이름을 바꿀 수도 있습니다. "Example"또는 이름과 같은 최상위 클래스가있는 여러 모델 클래스가 제공됩니다. 그것은 두 개의 필드로 구성

public class Example { 
@SerializedName("geocoded_waypoints") 
@Expose 
private List<GeocodedWaypoint> geocodedWaypoints = new ArrayList<GeocodedWaypoint>(); 
@SerializedName("routes") 
@Expose 
private List<Route> routes = new ArrayList<Route>(); 

프로젝트에 모든 클래스를 추가하고 방금과 같은 기본 클래스에 jsonString을 구문 분석보다 :

Example mainClassObject = new Gson().fromJson(jsonString, Example.class); 

을 그리고 지금 당신이이 개체에서 경로를 액세스 할 수 있습니다. 그리고 경로에서 다리까지 더 깊고 깊게 ...

0

제공 JSON 키 값을 구문 분석하는 코드 아래에 시도하십시오 :

private void parseJson(String jsonString){ 
     ArrayList<String> legsDistanceList = new ArrayList<>(); 
     ArrayList<String> legStepsDistanceList = new ArrayList<>(); 
     try{ 
      JSONObject rootJson = new JSONObject(jsonString); 
      if(rootJson.has("routes")) { 
       JSONArray routesJsonArray = rootJson.getJSONArray("routes"); 
       for(int i=0;i<routesJsonArray.length();i++){ 
        JSONObject routeJson = routesJsonArray.getJSONObject(i); 
        if(routeJson.has("legs")){ 
         JSONArray legsJsonArray = routeJson.getJSONArray("legs"); 
         for(int j=0;j<legsJsonArray.length();j++){ 
          JSONObject legJson = legsJsonArray.getJSONObject(j); 
          if(legJson.has("distance")){ 
           JSONObject distanceJson = legJson.getJSONObject("distance"); 
           legsDistanceList.add(distanceJson.getString("text")); 
          } 
          if(legJson.has("steps")){ 
           JSONArray stepsJsonArray = legJson.getJSONArray("steps"); 
           for(int k=0;k<stepsJsonArray.length();k++){ 
            JSONObject stepJson = stepsJsonArray.getJSONObject(k); 
            if(stepJson.has("distance")){ 
             JSONObject stepDistanceJson = stepJson.getJSONObject("distance"); 
             legStepsDistanceList.add(stepDistanceJson.getString("text")); 
            } 
           } 
          } 
         } 
        } 
       } 
      } 
     }catch (Throwable e){ 
      e.printStackTrace(); 
     } 

     Log.i("Legs Distance ",legsDistanceList.toString()); 
     Log.i("Legs Steps Distance ",legStepsDistanceList.toString()); 
    } 

나는 당신이이 단계에서 이해하기 어려울 수 있습니다 위의 코드를 생각하지만 당신은 미래 JSON 것이 것 더 도움이 당신에게 다음을 이해하면 물건을 파싱.

+0

정말 도움이되었으며 코드를 매우 쉽게 만들었습니다. 감사합니다. – Mamoon

0

파싱을 위해 제 3 자 (Gson, Logan Square 등)를 사용할 수 있습니다. 직접 액세스하려고하는 경우. 아래에서 샘플 코드를 찾아 "다리"배열에 액세스 할 수 있습니다.

은 우리가

JsonObject jsonObject = new JsonObject("json string"); 

이 "된 JSONObject는"당신이 "다리"배열에 액세스하려는 전체 JSON 값을 가정하자. 이 시나리오에서 "다리"배열은 "routes"배열 안에 있습니다. 그래서 우리는 먼저 "routes"배열을 가져 와서 그 배열을 반복하고 POJO 클래스에있는 각 객체와 저장소에서 "legs"배열을 얻거나 "distance"에서 "text"를 가져오고 싶다면 저장할 수 있다는 것을 의미합니다 그것은 당신이 필요로하는 arraylist 또는 문자열입니다. 다음은 텍스트 만 가져 오는 샘플 코드입니다.

JsonArray routesArray = jsonObject.optJsonArray("routes"); 
     if (routesArray != null) { 
      for (int i = 0; i < routesArray.length(); i++) { 
       JsonArray legsArray = routesArray.get(i).optJsonArray("legs"); 
       if (legsArray != null) { 
        for (int i = 0; i < legsArray.length(); i++) { 
         JsonObject legObject = legsArray.get(i); 
         JsonObject distanceObject = legObject.optJsonObject("distance"); 
         String textValue = distanceObject.optString("text"); 
        } 
       } 
      } 
     } 

희망이 도움이됩니다 :)

관련 문제