[英]JSONObject in JSONObject
I have an API Output like this: 我有这样的API输出:
{"user" : {"status" : {"stat1" : "54", "stats2" : "87"}}}
I create a simple JSONObject
from this API with: 我从这个API创建一个简单的JSONObject
:
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
? 但是如何获取stat1
和stat2
的数据?
JSONObject
provides accessors for a number of different data types, including nested JSONObjects
and JSONArrays
, using JSONObject.getJSONObject(String)
, JSONObject.getJSONArray(String)
. JSONObject
使用JSONObject.getJSONObject(String)
, JSONObject.getJSONArray(String)
为许多不同的数据类型提供访问器,包括嵌套的JSONObjects
和JSONArrays
。
Given your JSON, you'd need to do something like this: 鉴于您的JSON,您需要执行以下操作:
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. 注意这里缺少错误处理:例如代码假定存在嵌套成员 - 你应该检查null
- 并且没有异常处理。
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. 从您的响应用户和状态是对象,所以为此使用getJSONObject和stat1和stats2是状态对象键,所以为此使用getInt()方法获取整数值并使用getString()方法获取字符串值。
要访问JSON中的属性,可以使用JSON.parse解析对象,然后加入必需的属性,如:
var star1 = user.stat1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.