如何在 JSON 解析时检查元素是否存在?

How do I check if an element exists or not while JSON parsing?

我有以下 json 字符串。有时,有多个定义元素,有时只有一个。我是 JSON 解析的新手,我以某种方式以一种非常原始的方式设法获得了出现的第一个定义元素的值。但是,我无法获得定义的所有值,因为我无法在网上找到任何资源。我是否必须检查是否存在第二次出现或是否有更好的方法?

JSON:

{
  "metadata": {
    "provider": "Oxford University Press"
  },
  "results": [
    {
      "id": "edifice",
      "language": "en",
      "lexicalEntries": [
        {
          "entries": [
            {
              "etymologies": [
                "late Middle English: via Old French from Latin aedificium, from aedis dwelling + facere make"
              ],
              "grammaticalFeatures": [
                {
                  "text": "Singular",
                  "type": "Number"
                }
              ],
              "senses": [
                {
                  "definitions": [
                    "a large, imposing building."
                  ],
                  "id": "m_en_gb0256160.001",
                  "registers": [
                    "formal"
                  ]
                },
                {
                  "definitions": [
                    "a complex system of beliefs:"
                  ],
                  "examples": [
                    {
                      "text": "the concepts on which the edifice of capitalism was built"
                    }
                  ],
                  "id": "m_en_gb0256160.002",
                  "registers": [
                    "formal"
                  ]
                }
              ]
            }
          ],
          "language": "en",
          "lexicalCategory": "Noun",
          "pronunciations": [
            {
              "audioFile": "http://audio.oxforddictionaries.com/en/mp3/edifice_gb_1.mp3",
              "dialects": [
                "British English"
              ],
              "phoneticNotation": "IPA",
              "phoneticSpelling": "ˈɛdɪfɪs"
            }
          ],
          "text": "edifice"
        }
      ],
      "type": "headword",
      "word": "edifice"
    }
  ]
}

Java 获取定义值的片段:

String locations = data.getJSONArray("results").getJSONObject(0).getJSONArray("lexicalEntries").getJSONObject(0).getJSONArray("entries").getJSONObject(0).getJSONArray("senses").getJSONObject(0).get("definitions").toString();

一切看起来都不错,但你应该在 getJSONArray("senses") 上停下来。

应该是

JSONArray senses= .....getJSONArray("senses");

然后您应该遍历该数组的元素。像这样。

ArrayList<String> definitions = new ArrayList<String>();
for(int i =0; i < senses.length(); i++){
    definitions.add(senses.getJSONObject(i).optString("definitions","");
}

但在这样做之前,您应该注意到您的定义 json 格式不正确,应该类似于

"definitions":"blablabl blablab"

因为不是数组;.