我有这个 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"
}
]
}
}
关于java - 如何返回整个 JSONObject?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42184198/