如何解析Java中的JSON数组? [英] How do I parse a JSON array in Java?
本文介绍了如何解析Java中的JSON数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下JSON文本,并希望获取值"detest"和"dislike".
I have the following JSON text and would like to get the values "detest" and "dislike".
{
"noun": {
"syn": [
"hatred",
"emotion"
],
"ant": [
"love"
]
},
"verb": {
"syn": [
"detest",
"dislike"
],
"ant": [
"love"
]
}
}
我尝试使用org.json库将其解析为以下内容:
I've tried parsing it using the org.json library with the following:
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.
推荐答案
以下内容与 JSON.simple 库.
您需要一个JSONParser
实例才能从String
对象中获取一个JSONObject
值.
You need a JSONParser
instance to get a JSONObject
value from your String
object.
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");
这篇关于如何解析Java中的JSON数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文