Home » Android » java – JSONObject in JSONObject

java – JSONObject in JSONObject

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have an API Output like this:

{"user" : {"status" : {"stat1" : "54", "stats2" : "87"}}}

I create a simple JSONObject from this API with:

JSONObject json = getJSONfromURL(URL);

After this I can read the data for User like this:

String user = json.getString("user");

But how do I get the Data for stat1 and stat2?

How to&Answers:

JSONObject provides accessors for a number of different data types, including nested JSONObjects and JSONArrays, using JSONObject.getJSONObject(String), JSONObject.getJSONArray(String).

Given your JSON, you’d need to do something like this:

JSONObject json = getJSONfromURL(URL);
JSONObject user = json.getJSONObject("user");
JSONObject status = user.getJSONObject("status");
int stat1 = status.getInt("stat1");

Note the lack of error handling here: for instance the code assumes the existence of the nested members – you should check for null – and there’s no Exception handling.

Answer:

JSONObject mJsonObject = new JSONObject(response);
JSONObject userJObject = mJsonObject.getJSONObject("user");
JSONObject statusJObject = userJObject.getJSONObject("status");
String stat1 = statusJObject.getInt("stat1");
String stats2 = statusJObject.getInt("stats2");

from your response user and status is Object so for that use getJSONObject and stat1 and stats2 is status object key so for that use getInt() method for getting integer value and use getString() method for getting String value.

Answer:

To access properties in an JSON you can parse the object using JSON.parse and then acceess the required property like:

var star1 = user.stat1;