[英]How do I check if an element exists or not while JSON parsing?
I have the following json string. 我有以下json字符串。 Sometimes, there are multiple definition elements and sometimes there is only one.
有时,有多个定义元素,有时只有一个。 I am new to JSON parsing and I somehow, in a very primitive way, managed to get the value of the first definition element that occurs.
我是JSON解析的新手,我以某种非常原始的方式设法获得了出现的第一个定义元素的值。 However, I am unable to get all values of definitions since there is no resource that I can find online.
但是,由于没有在线资源,我无法获得所有定义值。 Do I have to check if second occurrence exists or is there a better way to do it ?
我是否必须检查是否存在第二种情况?是否有更好的方法来进行处理?
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 snippet to get definition value: Java代码段以获取定义值:
String locations = data.getJSONArray("results").getJSONObject(0).getJSONArray("lexicalEntries").getJSONObject(0).getJSONArray("entries").getJSONObject(0).getJSONArray("senses").getJSONObject(0).get("definitions").toString();
Everything looks good but you should stop at getJSONArray("senses"). 一切看起来都不错,但是您应该在getJSONArray(“ senses”)处停止。
It should be 它应该是
JSONArray senses= .....getJSONArray("senses");
and then you should loop thru elements of that array. 然后应该遍历该数组的元素。 Something like this.
这样的事情。
ArrayList<String> definitions = new ArrayList<String>();
for(int i =0; i < senses.length(); i++){
definitions.add(senses.getJSONObject(i).optString("definitions","");
}
But before doing that you should notice that your definitions json is not well formed it should be someting like 但是在此之前,您应该注意您的定义json格式不正确,应该像
"definitions":"blablabl blablab"
Since it is not an array;. 由于它不是数组;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.