如何在 Java 中解析 JSON 数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29039534/
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
How do I parse a JSON array in Java?
提问by user4668503
I have the following JSON text and would like to get the values "detest" and "dislike".
我有以下 JSON 文本,并希望获得值“detest”和“dislike”。
{
"noun": {
"syn": [
"hatred",
"emotion"
],
"ant": [
"love"
]
},
"verb": {
"syn": [
"detest",
"dislike"
],
"ant": [
"love"
]
}
}
I've tried parsing it using the org.json library with the following:
我尝试使用 org.json 库解析它,如下所示:
JSONArray obj = new JSONObject(String);
JSONArray arr = obj.getJSONArray("syn");
But I can't seem to access the array this way. Any help is greatly appreciated.
但我似乎无法以这种方式访问数组。任何帮助是极大的赞赏。
回答by Francesco Menzani
The following is related to the JSON.simplelibrary.
以下是与JSON.simple库相关的内容。
You need a JSONParser
instance to get a JSONObject
value from your String
object.
您需要一个JSONParser
实例来JSONObject
从您的String
对象中获取值。
JSONObject data;
try {
JSONParser helper = new JSONParser();
data = (JSONObject)helper.parse(String);
} catch (ParseException parse) {
// Invalid syntax
return;
}
// Note that these may throw several exceptions
JSONObject node = (JSONObject)data.get("verb");
JSONArray array = (JSONArray)node.get("syn");