JSONObject中的JSONObject

12

我有一个API输出,格式如下:

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

我使用以下代码从API创建了一个简单的JSONObject

JSONObject json = getJSONfromURL(URL);

接着,我可以这样读取用户的数据:

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

我应该如何获取stat1stat2的数据呢?

4个回答

29

JSONObject 提供访问多种不同数据类型的访问器,包括使用JSONObject.getJSONObject(String)JSONObject.getJSONArray(String)来访问嵌套的JSONObjectsJSONArrays

给定您的 JSON 数据,您需要像这样执行:

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

注意这里缺乏错误处理:例如,代码假定嵌套成员存在 - 您应该检查null - 并且没有异常处理。


你是指 JSONObject user = json.getJSONObject("user") 吗? - Che Jami

2
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");

根据您的回复,userstatus都是对象,因此可以使用getJSONObject方法获取对象,并且stat1stats2status对象的键,所以可以使用getInt()方法获取整数值,使用getString()方法获取字符串值。


1

要访问JSON中的属性,您可以使用JSON.parse解析对象,然后访问所需的属性,例如:

var star1 = user.stat1;

0

使用Google Gson库...

Google Gson是一个简单的基于Java的库,用于将Java对象序列化为JSON格式,反之亦然。它是由Google开发的开源库。

// Here I'm getting a status object inside a user object. Because We need two fields in user object itself.
JsonObject statusObject= tireJsonObject.getAsJsonObject("user").getAsJsonObject("status");
// Just checking whether status Object has stat1 or not And Also Handling NullPointerException.
String stat1= statusObject.has("stat1") && !statusObject.get("stat1").isJsonNull() ? statusObject.get("stat1").getAsString(): "";
// 
String stat2= statusObject.has("stat2") && !statusObject.get("stat2").isJsonNull() ? statusObject.get("stat2").getAsString(): "";
 

如果您有任何疑问,请在评论中告知...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接