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

相关文章:

java - org.springframework.beans.factory.BeanCreationException : Error creating bean with name 'triangle' defined in class path resource

c# - 在 C# 中,当一个字段可能是字符串或字符串数​​组时,如何反序列化此 json?

json - 使用 crate 的 HTTP API 插入对象数组 : error 4003

c - 如何用C语言解析XML标签中的值?

java - 如何修复此正则表达式?

java - Glassfish 上 mobicents SccpAddress 中的 NoSuchMethodError

java - 通过jsp页面将表单数据插入到数据库中两个不同的表中

python - InfluxDB 缺少标签值(putInfluxDB nifi 处理器)

java - 使用UML2解析XMI文件,如何处理href属性?

string - 从字符串中解析可用的街道地址、城市、州、邮政编码