简体   繁体   中英

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.

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 .

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM