【发布时间】:2015-07-01 05:31:41
【问题描述】:
我有一个需要解析的 JSONArray。但是,问题是其中一个对象只有一个字段,其余对象有两个字段。
{"Event":{
"Details":[
{
"Key" : "AA",
"Value" : "a"
},
{
"Key" : "BB",
"Value" :"B"
},
{
"Key" :"CC"
},
{
"Key" :"MIN",
"Value" : -1
}
]
}}
所以,现在当我使用这段代码解析它时
private void parse(String jsonStr) throws JSONException{
String Value, Key;
JSONObject obj = new JSONObject(jsonStr);
JSONArray array = obj.getJSONObject("Event").getJSONArray("Details");
for(int i = 0; i < array.length(); i++) {
Key = array.getJSONObject(i).getString("Key");
if(Key.equals("CC")){ // make case for null here
Value = "Something was supposed to be here";
}
Object type = array.getJSONObject(i).get("Value");
//System.out.println("Type: \n"+type.getClass().getSimpleName());
if(type instanceof String) {
String ValueStr=array.getJSONObject(i).getString("Value");
System.out.println(ValueStr);
} else if(type instanceof Number) {
Integer ValueInt = array.getJSONObject(i).getInt("Value");
System.out.println(ValueInt);
}
}
}
读取“CC”后停止解析。它甚至不读取下一个值。 'Key' CC 的'Value' 有时为空,有时为字符串。那么,我该如何捕捉呢?另外,CC的Value为null时,如何继续解析下一个对象?
编辑: 所以,我放了一个 try-catch 块,但 for 循环甚至不再迭代了。它只循环一次。
for(int i =0; i<array.length() ; i++)
{
Key = array.getJSONObject(i).getString("Key");
try
{
Object type = array.getJSONObject(i).get("Value");
//System.out.println("Type: \n"+type.getClass().getSimpleName());
if(type instanceof String)
{
String ValueStr = array.getJSONObject(i).getString("Value");
System.out.println(ValueStr);
}
else if(type instanceof Number)
{
Integer ValueInt = array.getJSONObject(i).getInt("Value");
System.out.println(ValueInt);
}
}
catch(JSONException e){
Value="something was supposed to be here";
}
}
【问题讨论】:
-
显然我也无法正确格式化我的代码。 ://
-
请先验证您的 json,` "Key" : "AA", "Value" : "a"` 应该是逗号分隔值,然后尝试您的代码
-
对不起,这是我打字的错误。 JSONArray 很好,它是在另一种方法中生成的。再次,对此感到抱歉。我现在编辑了它
-
@user270386:检查下面给出的答案。