Marc El Bichon
Marc El Bichon

Reputation: 407

Java read Json array in Json object

I have a String like this:

{"api_authentication":{"api_response":{"token":"XXXXXXXXXXXXXXXXXXXXXXXXX","firstname":"John","disabled":false,"attempts":0,"id":123,"lastname":"Malkovitch","expire":false,"status":0}}}

I can turn this string into an object:

JSONObject jobj = new JSONObject(response);

But I don't find how to get the token value, I tried creating JSONArrays but i get a not found exception.

Upvotes: 0

Views: 286

Answers (3)

lema
lema

Reputation: 498

You could try something like:

Object tokenValue =  jobj.getJSONObject("api_authentication").getJSONObject("api_response").get("token");

After that you can cast the object to the desired type or use something like getString(.) straightaway.

Upvotes: 0

Harshith Rai
Harshith Rai

Reputation: 3066

this might work by the look of what you have posted. The posted code snippet shows that it is a single JSON object and not a JSONArray. Hence try the following:

JSONObject jobj = new JSONObject(response);
String newtoken = jobj.getJSONObject("api_authentication").getJSONObject("api_response").getString("token"); //declare the variable `newtoken` somhwere before of a desired type

Upvotes: 1

drowny
drowny

Reputation: 2147

You can do it like this ;

final JSONObject api_authentication = jobj.getJSONObject("api_authentication");
final JSONObject api_response = api_authentication.getJSONObject("api_response");
System.out.println(api_response.getString("token"));

if JSON any value in curlybrackets { ... } , this is jsonObject . If values are in [ ... ], this is JsonArray. Also you can get which one is object or array, and get it relevant fields from this. So all of json elements are with curly bracket in your problem. Get it as JsonObject.

Upvotes: 3

Related Questions