[英]How to return whole JSONObject?
我有这个JSONFile
{"PostsDetails":[
{
"pageInfo": {
"pagePic": "http://example.com/abc.jpg",
"pageName": "abc"
},
"id": 1,
"posts": [
{
"likesCount": "2",
"nameOfPersonWhoPosted": "Jane Doe",
"post_id": "0987654321_123456789012",
"timeOfPost": "0987654321",
"actor_id": "0987654321",
"message": "Can't wait to see it!",
"picOfPersonWhoPosted": "http://example.com/abc.jpg"
}
]
}
]}
我有这种方法可以按posts数组中的post_id搜索
public JSONArray getPostList(String post_id) {
JSONObject jsonObject = JSONFileUtil2.getFileJSONObject();
JSONArray arr = (JSONArray) jsonObject.get("PostsDetails");
JSONArray returnArr = new JSONArray();
for (Object aJsonArray : arr) {
jsonObject = (JSONObject) aJsonArray;
JSONArray postsArr = (JSONArray) jsonObject.get("posts");
for (Object bJsonArray : postsArr) {
jsonObject= (JSONObject) bJsonArray;
if (jsonObject.get("post_id").equals(post_id)) {
returnArr.add(jsonObject);
}
}
}
return returnArr;
}
但是我只能得到这样的返回值。 我想返回整个对象,包括id,pageInfo和posts对象。 我怎样才能做到这一点?
[
{
"likesCount": "2",
"nameOfPersonWhoPosted": "Jane Doe",
"post_id": "0987654321_123456789012",
"timeOfPost": "0987654321",
"actor_id": "0987654321",
"message": "Can't wait to see it!",
"picOfPersonWhoPosted": "http://example.com/abc.jpg"
}
]
您可以通过首先访问迭代对象来访问找到的数组json对象; 您不会覆盖jsonObject来访问所需的对象:
for (Object aJsonArray : arr) {
JSONObject foundJsonObject = (JSONObject) aJsonArray;
JSONArray postsArr = (JSONArray) foundJsonObject.get("posts");
for (Object bJsonArray : postsArr) {
JSONObject postJsonObject= (JSONObject) bJsonArray;
if (postJsonObject.get("post_id").equals(post_id)) {
returnArr.add(foundJsonObject);
}
}
}
但请注意,您的返回对象将是JSONObject而不是JSONArray,如下所示:
{
{
"pageInfo": {
"pagePic": "http://example.com/abc.jpg",
"pageName": "abc"
},
"id": 1,
"posts": [
{
"likesCount": "2",
"nameOfPersonWhoPosted": "Jane Doe",
"post_id": "0987654321_123456789012",
"timeOfPost": "0987654321",
"actor_id": "0987654321",
"message": "Can't wait to see it!",
"picOfPersonWhoPosted": "http://example.com/abc.jpg"
}
]
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.