在的JSONObject的JSONObject [英] JSONObject in JSONObject

查看:125
本文介绍了在的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 ,使用<一个href=\"http://www.json.org/javadoc/org/json/JSONObject.html#getJSONObject%28java.lang.String%29\"><$c$c>JSONObject.getJSONObject(String), <一href=\"http://www.json.org/javadoc/org/json/JSONObject.html#getJSONArray%28java.lang.String%29\"><$c$c>JSONObject.getJSONArray(String).

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.

这篇关于在的JSONObject的JSONObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆