JSON解析不使用数组名称 [英] Parse JSON without using array name
本文介绍了JSON解析不使用数组名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用GSON解析。我能够使用解析JSON arrayName中,但是我并不想用arrayName中,因为它不是static.arrayName可以变化,更会从服务器添加。请建议。
JSON:
{
城市code:,
清单:{
一:
{
大人:2
},
{
大人:2
},
{
大人:2
}
]
三化:
{
大人:2
},
{
大人:2
},
{
大人:2
},
{
大人:2
},
{
大人:2
}
]
}
}
解决方案
这适用于你的案件。
请记住,JSONObject的具有列出它的所有属性keys()方法。你可以看到,迭代的结果是取消订购,运行此code和看到的结果。
静态无效parseJson(JSON字符串){
尝试{
的JSONObject对象=新的JSONObject(JSON); //获取名单的JSONObject
JSONObject的OBJ = object.getJSONObject(名单);
//尝试获取该对象的所有属性
@燮pressWarnings(未登记)
迭代器<串GT;迭代= obj.keys();
而(iterator.hasNext()){
字符串键= iterator.next();
JSONArray ARR = obj.getJSONArray(键);
INT大小= arr.length();
的for(int i = 0; I<大小;我++){
JSONObject的O = arr.getJSONObject(I)
Log.e(JSON,=>中+ o.getInt(成人));
}
}
}赶上(JSONException E){
e.printStackTrace();
}
}
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
}
]
}
}
解决方案
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();
}
}
这篇关于JSON解析不使用数组名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文