【问题标题】:Android: Parse 2 jsonArray [closed]Android:解析 2 jsonArray [关闭]
【发布时间】:2015-07-21 06:32:14
【问题描述】:

如何在 Android 中解析 2 个 json 数组? 请看下面的代码;

    {
"detail": [
    {
        "price": 51,
        "numsc": 2,
        "name": "this app is about animals",
        "sc1": "printed-dress.jpg",
        "sc2": "printed-dress2.jpg"
    }
],
"colors": [
    {
        "color": "#5D9CEC",
        "name": "blue"
    },
    {
        "color": "#FCCACD",
        "name": "pink"
    }
]

}

你能帮我吗??

【问题讨论】:

  • 这里是一个对象,一个对象中有一个数组,解析有什么问题?

标签: android json


【解决方案1】:
JSONObject object  = new JSONObject(your-string);

    JSONArray details=object.getJSONArray("details");
for(int j=0;j<details.length();j++){
       JSONObject detail= details.getJSONObject(i);
    String price = detail.getString("price");
    ....
    }
    JSONArray colors = object.getJSONArray("colors");

    for(int i=0;i<colors.length();i++){
       JSONObject obj= colors.getJSONObject(i);
       // parse your json here
    String color = obj.getString("color")

    }

【讨论】:

  • "detail" 是 JSONArray 而不是 JSONObject。
  • 谢谢!? 工作正常。
【解决方案2】:

见以下代码:

private void decodeJSON()
    {
        String JSONString = "you json String";
        try
        {
            JSONObject obj = new JSONObject(JSONString);
            JSONArray arr = obj.getJSONArray("detail");
            JSONObject detail = arr.getJSONObject(0);
            int price = detail.getInt("price"); // do same thing to get other values


            arr = obj.getJSONArray("colors");
            JSONObject color = arr.getJSONObject(0);
            String colorValue = color.getString("color");
            String name = color.getString("name");

            // do same thing for next object in array.
        } catch (JSONException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

【讨论】:

    猜你喜欢
    • 2016-08-17
    • 2016-08-12
    • 2017-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多