问题
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