使用 Java 访问 JSONArray 中项目的成员
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1568762/
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
Accessing members of items in a JSONArray with Java
提问by minimalpop
I'm just getting started with using json with java. I'm not sure how to access string values within a JSONArray. For instance, my json looks like this:
我刚刚开始使用 json 和 java。我不确定如何访问 JSONArray 中的字符串值。例如,我的 json 如下所示:
{
"locations": {
"record": [
{
"id": 8817,
"loc": "NEW YORK CITY"
},
{
"id": 2873,
"loc": "UNITED STATES"
},
{
"id": 1501
"loc": "NEW YORK STATE"
}
]
}
}
my code:
我的代码:
JSONObject req = new JSONObject(join(loadStrings(data.json),""));
JSONObject locs = req.getJSONObject("locations");
JSONArray recs = locs.getJSONArray("record");
I have access to the "record" JSONArray at this point, but am unsure as to how I'd get the "id" and "loc" values within a for loop. Sorry if this description isn't too clear, I'm a bit new to programming.
此时我可以访问“记录”JSONArray,但不确定如何在 for 循环中获取“id”和“loc”值。对不起,如果这个描述不太清楚,我对编程有点陌生。
采纳答案by notnoop
Have you tried using JSONArray.getJSONObject(int), and JSONArray.length()to create your for-loop:
您是否尝试过使用JSONArray.getJSONObject(int)和JSONArray.length()来创建您的 for 循环:
for (int i = 0; i < recs.length(); ++i) {
JSONObject rec = recs.getJSONObject(i);
int id = rec.getInt("id");
String loc = rec.getString("loc");
// ...
}
回答by Teja Kantamneni
By looking at your code, I sense you are using JSONLIB. If that was the case, look at the following snippet to convert json array to java array..
通过查看您的代码,我感觉到您正在使用 JSONLIB。如果是这种情况,请查看以下代码段将 json 数组转换为 java 数组。
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( input );
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setArrayMode( JsonConfig.MODE_OBJECT_ARRAY );
jsonConfig.setRootClass( Integer.TYPE );
int[] output = (int[]) JSONSerializer.toJava( jsonArray, jsonConfig );
回答by Piko
An org.json.JSONArrayis not iterable.
Here's how I process elements in a net.sf.json.JSONArray:
一个org.json.JSONArray不迭代。
以下是我如何处理net.sf.json.JSONArray中的元素:
JSONArray lineItems = jsonObject.getJSONArray("lineItems");
for (Object o : lineItems) {
JSONObject jsonLineItem = (JSONObject) o;
String key = jsonLineItem.getString("key");
String value = jsonLineItem.getString("value");
...
}
Works great... :)
效果很好... :)
回答by wired00
In case it helps someone else, I was able to convert to an array by doing something like this,
如果它对其他人有帮助,我可以通过执行以下操作将其转换为数组,
JSONObject jsonObject = (JSONObject)new JSONParser().parse(jsonString);
((JSONArray) jsonObject).toArray()
...or you should be able to get the length
...或者你应该能够得到长度
((JSONArray) myJsonArray).toArray().length
回答by prayagupd
Java 8 is in the market after almost 2 decades, following is the way to iterate org.json.JSONArray
with java8 Stream API.
Java 8 在近 2 年后上市,以下是org.json.JSONArray
使用 java8 Stream API进行迭代的方式。
import org.json.JSONArray;
import org.json.JSONObject;
@Test
public void access_org_JsonArray() {
//Given: array
JSONArray jsonArray = new JSONArray(Arrays.asList(new JSONObject(
new HashMap() {{
put("a", 100);
put("b", 200);
}}
),
new JSONObject(
new HashMap() {{
put("a", 300);
put("b", 400);
}}
)));
//Then: convert to List<JSONObject>
List<JSONObject> jsonItems = IntStream.range(0, jsonArray.length())
.mapToObj(index -> (JSONObject) jsonArray.get(index))
.collect(Collectors.toList());
// you can access the array elements now
jsonItems.forEach(arrayElement -> System.out.println(arrayElement.get("a")));
// prints 100, 300
}
If the iteration is only one time, (no need to .collect
)
如果迭代只有一次,(不需要.collect
)
IntStream.range(0, jsonArray.length())
.mapToObj(index -> (JSONObject) jsonArray.get(index))
.forEach(item -> {
System.out.println(item);
});
回答by roger
HashMap regs = (HashMap) parser.parse(stringjson);
HashMap regs = (HashMap) parser.parse(stringjson);
(String)((HashMap)regs.get("firstlevelkey")).get("secondlevelkey");
(String)(( HashMap)regs.get("firstlevelkey")).get("secondlevelkey");