org.json.JSONObject$1 cannot be converted to JSONObject error while parsing json string

旧巷老猫 提交于 2019-12-13 09:17:26

问题


For parsing json i use JSONArray and 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"
        }]
    }

My problem is that when fetchObject get the null object it give me org.json.JSONObject$1 cannot be converted to JSONObject in try catch . Please help me how can i solve this.....Thanks for reading....


回答1:


if(obj.length() == 0)

is what I would do.

JSONObject fetchObject;

if(flowerArray.getJSONObject(i).length() !=0)

/

fetchObject = flowerArray.getJSONObject(i)
    if(fetchObject== null)



回答2:


After reading JsonArray and JsonObject doc i understand how to sort out this problem.

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();
        }
    }


来源:https://stackoverflow.com/questions/40632125/org-json-jsonobject1-cannot-be-converted-to-jsonobject-error-while-parsing-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!