我有以下json字符串。有时,有多个定义元素,有时只有一个。我是JSON解析的新手,我以某种非常原始的方式设法获得第一个定义元素的值。但是,我无法获得所有定义值,因为我没有可以在线找到的资源。我是否必须检查是否存在第二次出现或有更好的方法吗?
JSON:
ID CN
1 PHLSERVER01
1 NYCSFAX01
1 KONGRDATA01
1 LAXSERVER01
获取定义值的Java代码段:
{
"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"
}
]
}
答案 0 :(得分: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"
因为它不是数组;。