简体   繁体   中英

Parse JSON with 2 objects before an array

I'm currently trying to parse some JSON in my android application but I keep getting an error saying "No value for users"

This is the current code I am using:

JSONObject parentObject = new JSONObject(finalJSON);

            JSONObject childObject = new JSONObject(String.valueOf(parentObject));

            JSONArray parentArray = childObject.getJSONArray("users");

            JSONObject finalObject = parentArray.getJSONObject(0);

            String userName = finalObject.getString("username");

            String profileLink = finalObject.getString("profileimage");

            Log.d("JSON", String.valueOf(finalObject));

            return profileimage+ " - " + profileLink ;

and here is my JSON:

{
"reply": {
    "users": [
        {
            "userid": "001",
            "loggedIn": 1,
            "username": "joe.bloggs",
            "profileimage": "http://127.0.0.1/joebloggs.png",
            "realname": "Joe Bloggs",
        }
    ]

   }
}

Thanks in advance!

You forgot the reply level.

Here is what you should do.

JSONObject parentObject = new JSONObject(finalJSON);


JSONArray userArray = parentObject
                .getJSONObject("reply")
                .getJSONArray("users");

JSONObject finalObject = userArray.getJSONObject(0);

you can't take new object for object inside object.

you have to do this for parse object inside object.

JSONObject object1 =  new JSONObject(finalJSON);

JSONObject object2 =  object1.getJSONObject("reply");

JSONArray jsonArray = object2.getJSONArray("users");

JSONObject object3 =  jsonArray.getJSONObject(0);

try the following:

JSONObject root = null;
try {
    root = new JSONObject("reply");
    JSONArray childArray = root.getJSONArray("users");
    String userName = childArray.getString(0);
    .
    .
    .
} catch (JSONException e) {
    e.printStackTrace();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM