Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSONObject in JSONObject

Tags:

java

json

android

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?

like image 834
user1488243 Avatar asked Aug 02 '12 15:08

user1488243


2 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.

like image 115
pb2q Avatar answered Nov 13 '22 01:11

pb2q


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.

like image 41
Krunal Shah Avatar answered Nov 13 '22 01:11

Krunal Shah