首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何解析Java中的JSON?

如何解析Java中的JSON?
EN

Stack Overflow用户
提问于 2018-05-31 06:48:25
回答 2查看 0关注 0票数 0

我有以下JSON文本。如何可以解析它来获得pageNamepagePicpost_id,等?

代码语言:javascript
复制
{
   "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"
         }
    ]
}
EN

回答 2

Stack Overflow用户

发布于 2018-05-31 15:04:08

该org.json库易于使用。示例代码如下:

代码语言:javascript
复制
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");
    ......
}
票数 0
EN

Stack Overflow用户

发布于 2018-05-31 16:04:07

  1. 如果想从JSON创建JAVA对象,反之亦然,请使用GSON或JACKSON第三方JAR等。 //from object to JSON Gson gson = new Gson(); gson.toJson(yourObject); // from JSON to object yourObject o = gson.fromJson(JSONString,yourObject.class);
  2. 但是,如果只想分析一个JSON字符串并获取一些值(或者从头创建一个JSON字符串以通过线路发送),那么只需使用包含JsonReader,JsonArray,JsonObject等的JaveEE Jar。你可能想要下载该实现规格像javax.json。有了这两个jar,我可以解析JSON并使用这些值。 这些API实际上遵循XML的DOM / SAX分析模型。 Response response = request.get(); // REST call JsonReader jsonReader = Json.createReader(new StringReader(response.readEntity(String.class))); JsonArray jsonArray = jsonReader.readArray(); ListIterator l = jsonArray.listIterator(); while ( l.hasNext() ) { JsonObject j = (JsonObject)l.next(); JsonObject ciAttr = j.getJsonObject("ciAttributes");
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100004669

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档