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/61055558/

相关文章:

java - Kafka ACL - LEADER_NOT_AVAILABLE

java - 删除 Spring MVC 网站中的 ThreadLocal 对象?

iphone - 通过 JSON 传递西类牙语数据

java - 仅打印 JSON 中的两个值

mysql - 使用 JSON_SEARCH 匹配 json 数据中的整数

java - 修复 XML 文件中的错误编码

php - BeautifulSoup 和 php/html 文件

java - 如何通过 while 循环一次处理输入一个数字

java - DBUnit:NoSuchColumnException ColumnNameToIndexes 缓存映射中的非大写输入列。 map 的列名不区分大小写

javascript - 使用原生 javascript 从 json 解析 html 代码