Java 需要一些帮助来解析来自后端服务器的JSON响应吗
目前正在使用android应用程序,我需要关于如何提取此json对象的responses字段中的子字段的帮助: 目前,我正在执行以下操作以提取其他一些字段:Java 需要一些帮助来解析来自后端服务器的JSON响应吗,java,android,json,Java,Android,Json,目前正在使用android应用程序,我需要关于如何提取此json对象的responses字段中的子字段的帮助: 目前,我正在执行以下操作以提取其他一些字段: JSONObject json = new JSONObject(response2); int id = json.getInt("id"); String desc = json.getString("description"); JSONObject json2 = json.getJSONObject("owner");
JSONObject json = new JSONObject(response2);
int id = json.getInt("id");
String desc = json.getString("description");
JSONObject json2 = json.getJSONObject("owner");
String username = json2.getString("userName");
您需要创建逻辑来解析数据。JSON字符串中的每一项都在您使用创建的
JSONObject
中
JSONObject json = new JSONObject(response2);
你所做的一切都是正确的。只需使用JSONObject
和JSONArray
类中可用的相应方法来移动对象
从主对象开始
{ // <-- this is your main object (AKA JSONObject json = new JSONObject(response2))
"id": 1, // to pull this id use json.getInt("id");
"title": "some text here", // to pull this title use json.getString("title");
...
"owner": { // Here's the logic part, owner is itself, a JSON object. so now you must extract it and parse through it.
// to pull the "owner" JSON object, use JSONObject ownerObject = json.getJSONObject("owner");
"userId": 1, // Now use the ownerObject to pull it's values. ownerObject.getInt("userId");
"userName": "TestingUser", // to pull this userName use ownerObject.getString("userName");
...
}
...
}
然后你会打电话:
JSONArray someJSONArray = getJSONArray("someJSONArray");
// Get each object from the array.
JSONObject object1 = someJSONArray.getJSONObject(0);
JSONObject object2 = someJSONArray.getJSONObject(1);
JSONArray someKeyArray = getJSONArray("someKey");
for (int i = 0; i < someKeyArray.length(); i++) {
// Extract the value.
int itemValue = someKeyArray.getInt(i);
}
或者如果数组包含字符串,例如:
"someJSONArray": [{ "id": 1, "userName": "TestingUser1" }, { "id": 2, "userName": "TestingUser2" }]
"someKey": [ 23, 435, 123, 6345, 123 ]
然后你会打电话:
JSONArray someJSONArray = getJSONArray("someJSONArray");
// Get each object from the array.
JSONObject object1 = someJSONArray.getJSONObject(0);
JSONObject object2 = someJSONArray.getJSONObject(1);
JSONArray someKeyArray = getJSONArray("someKey");
for (int i = 0; i < someKeyArray.length(); i++) {
// Extract the value.
int itemValue = someKeyArray.getInt(i);
}
JSONArray someKeyArray=getJSONArray(“someKey”);
对于(int i=0;i
数据就在那里,你只需要解析它 所以。。。问题是什么?如果你检查了图片,我试图提取响应字段和其中的子字段,但不确定“不确定如何”如何不是问题,并给出文本而不是图片。它是一个数组,所以使用
getJSONArray
。我理解你发布的内容,但我对如何处理响应感到困惑,我相信这是一个数组,所以我应该这样做:JSONArray someJSONArray=getJSONArray(“responses”);JSONObject object1=someJSONArray.getJSONObject(0);