在的JSONObject的JSONObject

问题描述:

我有一个API输出是这样的:

I have an API Output like this:

{"user" : {"status" : {"stat1" : "54", "stats2" : "87"}}}

我创建了一个简单的的JSONObject 此API使用:

JSONObject json = getJSONfromURL(URL);

这之后,我可以读取数据的用户是这样的:

After this I can read the data for User like this:

String user = json.getString("user");

但我怎么得到的数据为 STAT1 STAT2

的JSONObject 提供访问了许多不同的数据类型,包括嵌套的一个JSONObjects JSONArrays ,使用JSONObject.getJSONObject(String)$c$c>, JSONObject.getJSONArray(String)$c$c>.

JSONObject provides accessors for a number of different data types, including nested JSONObjects and JSONArrays, using JSONObject.getJSONObject(String), JSONObject.getJSONArray(String).

鉴于你的JSON,你需要做这样的事情:

Given your JSON, you'd need to do something like this:

JSONObject json = getJSONfromURL(URL);
JSONObject user = json.getJSONObject("user");
JSONObject status = user.getJSONObject("status");
int stat1 = status.getInt("stat1");

请注意缺少的错误处理:比如code假定嵌套成员的存在 - 你应该检查 - 而且也没有异常处理

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.