如何在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 14:34:46  来源:igfitidea点击:

How do I parse a JSON array in Java?

javajson

提问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 JSONParserinstance to get a JSONObjectvalue from your Stringobject.

您需要一个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");