不使用数组名解析 JSON
Parse JSON without using array name
我正在使用 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
}
]
}
}
您的 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
}
]
}
分享你的服务器端代码。
这适用于您的情况。
请记住,JSONObject 具有列出其所有属性的 keys() 方法。你可以看到,迭代器结果是无序的,运行这段代码并查看结果。
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();
}
}
我正在使用 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
}
]
}
}
您的 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
}
]
}
分享你的服务器端代码。
这适用于您的情况。 请记住,JSONObject 具有列出其所有属性的 keys() 方法。你可以看到,迭代器结果是无序的,运行这段代码并查看结果。
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();
}
}