2016-12-28 62 views
0

我有以下json字符串。有时,有多个定义元素,有时只有一个。我是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(); 

回答

1

一切看起来不错,但你应该getJSONArray停止( “感官”)。

应该

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" 

因为它不是一个阵列之前;.

+0

它工作。这是我在网上找到的一个API。谢谢。干杯 –