Android 不使用数组名解析JSON
我正在使用GSON进行解析。我可以使用arrayName解析json,但我不想使用arrayName,因为它不是静态的。arrayName可以更改,更多内容将从服务器添加。请建议 JSON:Android 不使用数组名解析JSON,android,json,gson,Android,Json,Gson,我正在使用GSON进行解析。我可以使用arrayName解析json,但我不想使用arrayName,因为它不是静态的。arrayName可以更改,更多内容将从服务器添加。请建议 JSON: { "cityCode": "", "list": { "one": [ { "adults": 2 }, { "adults": 2
{
"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();
}
}
静态空解析json(字符串json){
试一试{
JSONObject对象=新的JSONObject(json);
//获取“列表”JSONObject
JSONObject obj=object.getJSONObject(“列表”);
//尝试获取该对象的所有属性
@抑制警告(“未选中”)
迭代器迭代器=obj.keys();
while(iterator.hasNext()){
String key=iterator.next();
JSONArray arr=obj.getJSONArray(key);
int size=arr.length();
对于(int i=0;i”+o.getInt(“成人”);
}
}
}捕获(JSONException e){
e、 printStackTrace();
}
}
您的Json非常糟糕。根据您的要求,您应该首先使用Json。我同意u,但我无法更改Json格式,因此是否有可能使用数组名解析它?如果不更改格式,则不可能。因为您不确定静态索引的总数。谢谢您的代码,但我使用的是Gson,那么如何使用json pojo呢