java - 如何在Java中解析JSON

标签 java json parsing

我有以下 JSON 文本。如何解析它以获取 pageNamepagePicpost_id 等值?

{
  "pageInfo": {
    "pageName": "abc",
    "pagePic": "http://example.com/content.jpg"
  },
  "posts": [
    {
      "post_id": "123456789012_123456789012",
      "actor_id": "1234567890",
      "picOfPersonWhoPosted": "http://example.com/photo.jpg",
      "nameOfPersonWhoPosted": "Jane Doe",
      "message": "Sounds cool. Can't wait to see it!",
      "likesCount": "2",
      "comments": [],
      "timeOfPost": "1234567890"
    }
  ]
}

最佳答案

org.json库易于使用。

只需记住(在转换或使用诸如 getJSONObjectgetJSONArray 之类的方法时)JSON 表示法

  • [ … ] 表示一个数组,因此库会将其解析为 JSONArray
  • { … } 表示一个对象,因此库会将其解析为 JSONObject

示例代码如下:

import org.json.*;

String jsonString = ... ; //assign your JSON String here
JSONObject obj = new JSONObject(jsonString);
String pageName = obj.getJSONObject("pageInfo").getString("pageName");

JSONArray arr = obj.getJSONArray("posts"); // notice that `"posts": [...]`
for (int i = 0; i < arr.length(); i++)
{
    String post_id = arr.getJSONObject(i).getString("post_id");
    ......
}

您可以从以下位置找到更多示例:Parse JSON in Java

可下载的jar:http://mvnrepository.com/artifact/org.json/json

关于java - 如何在Java中解析JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57472203/

相关文章:

parsing - 使用 ANTLR 捕获(并保留)所有评论

从 google api 解析 xml 数据

java - 带 channel 的 Wicket 口氛围示例

ios - 是否可以使用 ObjectMapper 创建 JSON?

java - 具有更新用户提供服务的 Cloud Foundry

javascript - 即使值确实存在,Jquery 也不附加值

java - Java 中的 String contains () 即使字符串存在也会返回 false

java - 如何让EntityManager在DAO Factory中正常工作?

java - 通过单击 View 检查 Espresso 是否启动了新 Activity

c++ - 解析示例文本文件并将其拆分