[英]How to return whole JSONObject?
I have this JSONFile 我有这个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"
}
]
}
]}
And I have this method to search by post_id in posts array 我有这种方法可以按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;
}
But Im only getting a return value like this. 但是我只能得到这样的返回值。 I want to return the whole object including the id, pageInfo and posts object. 我想返回整个对象,包括id,pageInfo和posts对象。 How can I do that? 我怎样才能做到这一点?
[
{
"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"
}
]
You can access to your found array json object by access to first for iteration object; 您可以通过首先访问迭代对象来访问找到的数组json对象; you don't overwrite jsonObject to access your desire object: 您不会覆盖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);
}
}
}
but attention that your return obejct will be a JSONObject not JSONArray like this : 但请注意,您的返回对象将是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.