简体   繁体   English

Java在Json对象中读取Json数组

[英]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. 但是我没有找到如何获取令牌值的方法,我尝试创建JSONArrays,但是却找不到一个异常。

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 . 如果JSON在curlbrackets { ... }为任何值,则为jsonObject If values are in [ ... ] , this is JsonArray . 如果值在[ ... ] ,则为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. 因此,所有json元素在您的问题中都带有大括号。 Get it as JsonObject . 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. 发布的代码段显示它是单个JSON对象,而不是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. 之后,您可以将对象转换为所需的类型,也可以直接使用类似getString(.)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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