【问题标题】:Accessing an array inside an array in json response在json响应中访问数组内的数组
【发布时间】:2015-02-25 14:25:45
【问题描述】:

我正在使用下面的代码来获取价格值。我可以得到价格的价值。然而,当涉及到地壳时,它就例外了。

@Override
    public void onTaskCompleted(JSONArray responseJson) {

        try {
            List<String> crust = new ArrayList<String>();   
            List<String> price = new ArrayList<String>();

            for (int i = 0; i < responseJson.length(); ++i) {
                JSONObject object = responseJson.getJSONObject(i);

                if ((object.getString("MainCategoryID")).equals("1")
                        && (object.getString("SubCategoryID")).equals("1")) {
                    Log.i("Price ", object.getString("Price"));
                    price.add(object.getString("Price"));
                    Log.i("Crust ", object.getString("Crust"));
                    crust.add(object.getString("Crust"));

                }

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

这是 json 响应

{  
      "Category":"1PI",
      "Price":0.0000,
      "SubCategoryID":1,
      "SubMenu":true,
      "SubMenuEntity":[  
         {  
            "Crust":"Sausage",

Crust 位于数组内部的数组中,我如何在上面的编码中访问地壳。

任何帮助将不胜感激。

【问题讨论】:

  • “Crust 位于数组中,数组位于数组中”:不,Crust 位于 JSON 对象中的 JSON 数组中的 JSON 对象中。您需要做的就是获取SubMenuEntity(JSON 数组)的值并获取它包含的 JSON 对象,然后获取 Crust 名称/值对的值。
  • 从您的对象中获取 jsonArray 并从该数组中获取 Crust。我建议您在解析 json 响应时使用 GSON,而且最好在您的项目中使用 JSON 库,例如为性能和可管理性进行改造。

标签: android jsonresponse


【解决方案1】:

SubMenuEntity 项目有一个对象数组。您需要获取数组并循环它。对于每个对象,获取 Crust 的值。

try {
      List<String> crust = new ArrayList<String>();
      List<String> price = new ArrayList<String>();

      JSONArray responseJson = null;

      for (int i = 0; i < responseJson.length(); ++i) {
        JSONObject object = responseJson.getJSONObject(i);

        if ((object.getString("MainCategoryID")).equals("1")
            && (object.getString("SubCategoryID")).equals("1")) {
          Log.i("Price ", object.getString("Price"));
          price.add(object.getString("Price"));

          JSONArray subMenuArray = object.getJSONArray("SubMenuEntity");
          for (int j = 0; j < subMenuArray.length(); ++j) {
            JSONObject subMenuObject = subMenuArray.getJSONObject(j);
            Log.i("Crust ", subMenuObject.getString("Crust"));
            crust.add(subMenuObject.getString("Crust"));
          }

        }

      }
    } catch (JSONException e) {
      e.printStackTrace();
    }

【讨论】:

    【解决方案2】:

    你的CrustSubMenuEntity里面,你应该使用object.getJSONArray("SubMenuEntity")得到这个,然后从这个数组中的第一个Object得到Crust

    【讨论】:

      猜你喜欢
      • 2020-12-11
      • 1970-01-01
      • 2018-04-10
      • 1970-01-01
      • 2016-07-23
      • 2017-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多