检查特定的JSON对象是否可用 [英] Check if a particular JSON Object is available or not
问题描述
我有以下JSON文件,必须将其转储到ArrayList中:
I have JSON File as below which has to be dumped into an ArrayList:
{
"main1" : [
{
"child1" : valueA,
"child2" : valueB,
"child3" : valueC,
},
{
"child1" : value1,
"child3" : value3,
},
],
"main2" : "valueMain2"
}
必须检查元素 child2
是否存在然后取值。您可以看到它没有出现在第二个数组中。
The element child2
has to be checked if it exists or not and then the value is taken. You can see that it doesn't appear in the second array.
我使用的是Native JSON(org.JSON)
Java代码如下:
I am using Native JSON (org.JSON) Java Code is below:
ArrayList<HashMap<String,String>> myList = new ArrayList<HashMap<String,String>>();
JSONObject json = <my_json_object>;
JSONObject getchild2;
JSONArray jArray = <my_json_object>.getJSONArray("main1");
for(int j = 0; j < jArray.length(), j++){
HashMap<String,String> map = new HashMap<String,String>();
map.put("First Value", jArray.getJSONObject(j).getString("child1"));
map.put("Third Value", jArray.getJSONObject(j).getString("child3"));
getchild2 = jArray.getJSONObject(j).getJSONObject("child2");
if(getchild2 == null){
map.put("Second Value", "Some Dummy Value");
} else {
map.put("Second Value", jArray.getJSONObject(j).getString("child2"));
}
myList.add(map);
}
我如何实现这一目标?
How can I achieve this?
< my_json_object>
使用本机URL解析,因为我在此处获得了URL请求的HTTP响应:< a href =http://mobisys.in/blog/2012/01/parsing-json-from-url-in-android/ =noreferrer> http://mobisys.in/blog/2012/01 / parsing-json-from-url-in-android /
<my_json_object>
uses native URL Parsing as I get the HTTP Response of a URL request found here: http://mobisys.in/blog/2012/01/parsing-json-from-url-in-android/
它不起作用,因为错误如下:
It doesn't work as error is below:
E/AndroidRuntime(664): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
推荐答案
无论如何,我通过一些谷歌搜索获得了解决方案:
我将其重新构建为,
Anyway, I got the solution with some Googling: I re-framed it as,
if (!jArray.getJSONObject(j).has("child2")) {
map.put("Second Value", "N.A");
} else {
map.put("Second Value", jArray.getJSONObject(j).getString("child2"));
}
创建JSONObject getchild2 = jArray.getJSONObject(j).getJSONObject(child2 );相当,没必要。
Creating the JSONObject getchild2 = jArray.getJSONObject(j).getJSONObject("child2"); was rather, unnecessary.
而且这很有效!有关详细信息,请参阅此处:检查JSON中是否存在子对象
And this works, rather perfectly! Refer this for more details: Checking if exists subObject in JSON
感谢大家的帮助!
这篇关于检查特定的JSON对象是否可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!