如何在Java中解析JSON

问题:

我有以下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库易于使用。示例代码如下:

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"); ...... } [/code] 您可能会发现以下其他示例:Parse JSON in Java
可下载的jar:http://mvnrepository.com/artifact/org.json/json

 
 
Code问答: http://codewenda.com/topics/python/
Stackoverflow: How to parse JSON in Java

*转载请注明本文链接以及stackoverflow的英文链接

发表评论

电子邮件地址不会被公开。 必填项已用*标注

36 + = 40