繁体   English   中英

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

由于它不是数组;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM