不使用数组名称解析JSON

时间:2015-07-01 07:11:20

标签: android json gson

我正在使用GSON进行解析。我能够使用arrayName解析json,但我不想使用arrayName,因为它不是static.arrayName可以更改,更多将从服务器添加。请建议。

JSON:

{
    "cityCode": "",
    "list": {
        "one": [
            {
                "adults": 2
            },
            {
                "adults": 2
            },
            {
                "adults": 2
            }
        ],
        "three": [
            {
                "adults": 2
            },
            {
                "adults": 2
            },
            {
                "adults": 2
            },
            {
                "adults": 2
            },
            {
                "adults": 2
            }
        ]
    }
}

2 个答案:

答案 0 :(得分:1)

这适用于您的情况。 请记住,JSONObject具有keys()方法,该方法列出了其所有属性。你可以看到,Iterator结果是无序的,运行此代码并查看结果。

static void parseJson(String json){
    try{
        JSONObject object = new JSONObject(json);

        //Get "list" JSONObject
        JSONObject obj = object.getJSONObject("list");
        //Try to get all attributes of that object
        @SuppressWarnings("unchecked")
        Iterator<String> iterator = obj.keys();
        while (iterator.hasNext()) {
            String key = iterator.next();
            JSONArray arr = obj.getJSONArray(key);
            int size = arr.length();
            for(int i = 0; i < size; i++){
                JSONObject o = arr.getJSONObject(i);
                Log.e("JSON", "=> "+o.getInt("adults"));
            }
        }
    }catch(JSONException e){
        e.printStackTrace();
    }
}

答案 1 :(得分:0)

你的Json应该如下所示。

{
    "cityCode": "",
    "list":[
            {
                "index":"one"
                "adults": 2
            },
            {
                "index":"one"
                "adults": 2
            },
            {
                "index":"one"
                "adults": 2
            },
            {
                "index":"three"
                "adults": 2
            },
            {
                "index":"three"
                "adults": 2
            },
            {
                "index":"three"
                "adults": 2
            },
            {
                "index":"three"
                "adults": 2
            },
            {
                "index":"three"
                "adults": 2
            }
        ]
}

分享您的服务器端代码。

相关问题