协慌网

登录 贡献 社区

Java 如何解析 JSON

2
88250
贡献值 91
贡献次数 2

对于如下 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"
         }
    ]
}

答案

1
88250
贡献值 163
贡献次数 1

org.json 小巧易用,示例代码如下:

import org.json.*;

JSONObject obj = new JSONObject(" .... ");
String pageName = obj.getJSONObject("pageInfo").getString("pageName");

JSONArray arr = obj.getJSONArray("posts");
for (int i = 0; i < arr.length(); i++)
{
    String post_id = arr.getJSONObject(i).getString("post_id");
    ......
}

这里可以找到更多示例:使用 Java 解析 JSON

jar 包下载:https://mvnrepository.com/artifact/org.json/json