【问题标题】:Get multiple Objects from Json Android从 Json Android 获取多个对象
【发布时间】:2016-10-11 11:51:29
【问题描述】:

我想从中获取数据,但它令人困惑,如何去做。 我想访问腿。在腿距离然后文本。 然后在步骤之后,在步骤中再次距离然后文本。

在“路线”==>“腿”-->距离-->文本中

然后获取驾驶步骤 "路线" ==> "腿" ==> "步数" --> 距离 --> 文字

首先是对象,然后是数组,对象太混乱了。任何帮助将不胜感激。

{
       "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[r@e@bA"
                         },
                         "start_location" : {
                            "lat" : 31.55462439999999,
                            "lng" : 74.3571711
                         },
                         "travel_mode" : "DRIVING"
                      },

【问题讨论】:

标签: android arrays json jsonobject


【解决方案1】:

手动方法:

简而言之,Json 为您提供对象 (beetwen { } ) 或数组 (beetwen [ ] )。要从 json 深处获取某物,您必须经历每个级别。你只放了 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[r@e@bA"
                     },
                     "start_location" : {
                        "lat" : 31.55462439999999,
                        "lng" : 74.3571711
                     },
                     "travel_mode" : "DRIVING"
                  }]
            }
           ]
      }
     ]

}

假设你有一个名为“jsonString”的字符串。你像这样创建 json 对象:

JSONObject jsonObject = new JSONObject(jsonString);

比你需要的“路由”是 json 数组(在 [] 大括号之间)。你创建这个数组,深入到你的主 jsonObject:

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

要遍历每个数组元素(即 json 对象),您可以这样迭代:

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

你的“腿”是这样的:

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

像上面一样越来越深。

自动

使用 Gson 库和一些 Json Pojo 解析器要容易得多。

您在 build.gradle 中导入 gson:

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

你可以使用这个parser。选择源类型“JSON”和“注释样式”Gson。将您的 json 放入文本框中,然后单击预览或下载 ZIP。你也可以把你的包名和主类名或稍后手动重命名。您将获得多个模型类,其中前一个称为“示例”或您的名字。它由两个字段组成:

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);

现在您可以从此对象访问路由。和路线的腿越来越深......

【讨论】:

    【解决方案2】:

    请尝试下面的代码来解析提供的 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 解析更有帮助。

    【讨论】:

    • 这真的很有帮助,而且你让代码变得非常简单,谢谢。
    【解决方案3】:

    您可以通过第三方(Gson、Logan Square 等)进行解析。如果您尝试直接访问它。您可以在下面找到访问“legs”数组的示例代码。

    让我们假设

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

    这个“jsonObject”是完整的 json 值,你想从中访问“legs”数组。在这种情况下,“legs”数组位于“routes”数组中。所以我们需要首先获取“路线”数组并循环该数组并从每个对象中获取“腿”数组并存储在 POJO 类中,或者如果您想单独从“距离”中获取“文本”意味着您可以存储你需要的数组列表或字符串中的那个。下面是单独获取文本的示例代码。

    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");
                        }
                    }
                }
            }
    

    希望这有帮助:)

    【讨论】:

      猜你喜欢
      • 2022-01-24
      • 2017-04-08
      • 1970-01-01
      • 2020-10-03
      • 2013-03-05
      • 2016-09-16
      • 2020-05-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多