对于解析json我使用JSONArray和JsonObject:
protected void parseJson()
{
JSONObject object=null;
try {
object=new JSONObject(json);
myArray=object.getJSONArray(MY_ARRAY);
Log.e("Array Length",""+myArray.length());
key_id=new String[myArray.length()];
key_name=new String[myArray.length()];
for (int i=0;i<=myArray.length();i++)
{
JSONObject fetchObject=myArray.getJSONObject(i);
key_id[i] = fetchObject.getString(KEY_ID);
key_name[i] = fetchObject.getString(KEY_NAME);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
JSON DATA:
{
"data": [{
"key": 1,
"myval": "hello"
}, {
"key": 1,
"myval": "hello"
}, {
"key": 1,
"myval": "hello"
}, null, {
"key": 1,
"myval": "hello"
}, {
"key": 1,
"myval": "hello"
}]
}
我的问题是,当fetchObject获取null对象时,它给我org.json.JSONObject$1
无法在try catch中转换为JSONObject。
请帮帮我怎样才能解决这个问题.....感谢阅读......
答案 0 :(得分:2)
if(obj.length() == 0)
就是我要做的。
JSONObject fetchObject;
if(flowerArray.getJSONObject(i).length() !=0)
/
fetchObject = flowerArray.getJSONObject(i)
if(fetchObject== null)
答案 1 :(得分:0)
在阅读JsonArray和JsonObject doc之后,我明白了如何解决这个问题。
protected void parseJson()
{
JSONObject object=null;
try {
object=new JSONObject(json);
myArray=object.getJSONArray(MY_ARRAY);
Log.e("Array Length",""+myArray.length());
key_id=new String[myArray.length()];
key_name=new String[myArray.length()];
for (int i=0;i<=myArray.length();i++)
{
JSONObject fetchObject=myArray.optJSONObject(i);
if(fetchObject==null)
{
//do nothing
}
else
{
key_id[i] = fetchObject.getString(KEY_ID);
key_name[i] = fetchObject.getString(KEY_NAME);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}