java 从 JSON 获取子数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17670100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get sub-array from JSON
提问by user2579475
I parsing some data from a json file. Here is my JSON File.
我从 json 文件中解析了一些数据。这是我的 JSON 文件。
[
{
"topic": "Example1",
"contact": [
{
"ref": [
1
],
"corresponding": true,
"name": "XYZ"
},
{
"ref": [
1
],
"name": "ZXY"
},
{
"ref": [
1
],
"name": "ABC"
},
{
"ref": [
1,
2
],
"name":"BCA"
}
] ,
"type": "Presentation"
},
{
"topic": "Example2",
"contact": [
{
"ref": [
1
],
"corresponding": true,
"name": "XYZ"
},
{
"ref": [
1
],
"name": "ZXY"
},
{
"ref": [
1
],
"name": "ABC"
},
{
"ref": [
1,
2
],
"name":"BCA"
}
] ,
"type": "Poster"
}
]
I can fetch and store data one by one. Like this one
我可以一一获取和存储数据。像这个
JSONArray getContactsArray = new JSONArray(jsonObject.getString("contact"));
for(int a =0 ; a < getContactsArray.length(); a++)
{
JSONObject getJSonObj = (JSONObject)getContactsArray.get(a);
String Name = getJSonObj.getString("name");
}
1)Now, my question is there any way to get all name
values for each array with single query.
2) Can I get all those values in an Array
?
1)现在,我的问题是有什么方法可以name
通过单个查询获取每个数组的所有值。2)我可以在一个中获得所有这些值Array
吗?
Please correct me, if I am doing anything wrong. Thank you.
请纠正我,如果我做错了什么。谢谢你。
回答by Ravi Thapliyal
Iteration cannot be avoided here as org.json
and other Json parsers as well provide random access to objects but not to their properties collectively (as a collection). So, you can't query something like "all name properties of all contact objects"unless you probably get a Json parser like Gsonto unmarshall it that way.
此处无法避免迭代,因为org.json
其他 Json 解析器也提供对对象的随机访问,但不提供对它们的共同属性(作为集合)的随机访问。因此,您不能查询诸如“所有联系人对象的所有名称属性”之类的内容,除非您可能获得像Gson这样的 Json 解析器以这种方式对其进行解组。
But, that's too much to just avoid a for
loop when you can definitely shorten the parse by making use of the appropriate API methods to avoid unnecessary object casts.
但是,for
当您可以通过使用适当的 API 方法来避免不必要的对象转换来缩短解析时,仅仅避免循环就太过分了。
JSONArray contacts = jsonObject.getJSONArray("contact");
String[] contactNames = new String[contacts.length()];
for(int i = 0 ; i < contactNames.length; i++) {
contactNames[i] = contacts.getJSONObject(i).getString("name");
}
回答by Juned Ahsan
回答by Tanu Garg
Try this:
试试这个:
Create JSONObject of your file and try to get array of all names and iterate it to get all values.
创建文件的 JSONObject 并尝试获取所有名称的数组并对其进行迭代以获取所有值。
public static String[] getNames(JSONObject jo) {
int length = jo.length();
if (length == 0) {
return null;
}
Iterator i = jo.keys();
String[] names = new String[length];
int j = 0;
while (i.hasNext()) {
names[j] = (String) i.next();
j += 1;
}
return names;
}