JSONObject to JSONObject

I have an API output like this:

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

I am creating a simple JSONObject from this API with:

 JSONObject json = getJSONfromURL(URL); 

After that, I can read the data for the user as follows:

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

But how do I get data for stat1 and stat2 ?

+8
java json android
source share
3 answers

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

Given your JSON, you 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 example, the code assumes the existence of nested elements - you must check for null - and there is no exception handling.

+19
source share
 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 answer, user and status is an object, so for this, use getJSONObject and stat1 and stats2 is status , so for this, use the getInt () method to get an integer value and use the getString () method to get a String value.

+2
source share

To access properties in JSON, you can parse the object using JSON.parse and then activate the required property, for example:

 var star1 = user.stat1; 
+1
source share

All Articles