Parse JSON without using array name

混江龙づ霸主 提交于 2019-12-13 18:31:43

问题


I'm using GSON for parsing. I'm able to parse json using arrayName but I don't want to use arrayName as it is not static.arrayName can be change and more will be added from server. Please suggest.

JSON:

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

回答1:


This works for your case. Remember that JSONObject has keys() method which list all its attributes. And you can see that, Iterator result is un-ordered, run this code and see result.

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



回答2:


Your Json should look like following.

{
    "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
            }
        ]
}

Share you server side code.



来源:https://stackoverflow.com/questions/31154735/parse-json-without-using-array-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!