2017-02-12 78 views
0

我有這個JSONFile如何返回整個JSONObject?

{"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帖子陣列

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

您可以通過首先訪問迭代對象來訪問找到的數組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" 
     } 
    ] 
    } 
} 
+0

我想你的代碼,但是我得到「複製本地變量jsonObject「。 –

+0

我修改代碼只顯示您的解決方案,我通過重命名存儲「posts」屬性的新對象來更正代碼。現在你可以使用代碼! – M2E67

+0

你可以使用一個普通的for循環來避免覆蓋你得到 –