java - 如何返回整个 JSONObject?

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

我有这个方法可以通过 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/

相关文章:

java - Java 应用程序中的 Main 方法

java - 将 JFrame 窗口置于最前面

java - 私钥和公钥的扩展

java - 拆分不能正常工作

java - 在 JavaFX FXML 中启动最大化的应用程序窗口无法正常工作

Java网络客户端: How to serialize to Pascal JSON?

java - 如何构建 REST dto?

javascript - jQuery 对话框弹出将 Json 返回到新页面而不是当前页面

java - 为每个选项卡 fragment 动态生成不同的内容(来自 JSON)

java - 使用 gson 和 back 进行序列化不适用于泛型类型