Anupam
Anupam

Reputation: 3752

JSON Object parsing

I need to parse some JSON object, whihc looks like this:

{"searchdata":{},"userdata":{"currency":"69","notificationCount":7}}

I using the following code to achieve this:

JSONObject rootObj = new JSONObject(getResponse);
JSONObject jSearchData = rootObj.getJSONObject("searchdata");
JSONObject userData = jSearchData.getJSONObject("userdata");

String currency = userData.getString("currency");

I'm not able to print the currency object from the above code. I keep getting exception:

Exception: org.json.JSONException: No value for userdata

I don't know what am I doing wrong.

Any kind of help will be appreciated.

Upvotes: 1

Views: 2469

Answers (2)

Blackbelt
Blackbelt

Reputation: 157457

JSONObject rootObj = new JSONObject(getResponse);

userData is inside rootObj not inside searchdata

For null value you should use:

isNull

if (!rootObj.isNull("userdata")) {
    JSONObject userData = rootObj.getJSONObject("userdata");
}

Upvotes: 10

Dhaval Parmar
Dhaval Parmar

Reputation: 18978

use

JSONObject userData = rootObj.getJSONObject("userdata");

to get currency

currency  = userData.getString("currency");

use like this way...

check object is null..

as per @blackbelt's answer use : if (!rootObj.isNull("userdata"))

Upvotes: 1

Related Questions