如何返回整个JSONObject?

时间:2017-02-12 04:25:49

标签: java json

我有这个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"
    }
   ]
 }
]}

我有这个方法通过post_id在posts数组中搜索

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"
 }
]

1 个答案:

答案 0 :(得分:1)

您可以通过首先访问迭代对象来访问找到的数组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);
           }
        }
   }

但注意你的返回obejct将是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"
      }
    ]
  }
}
相关问题