我有以下JSON文本。我如何解析它以获得pageName, pagePic, post_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"
    }
  ]
}

当前回答

几乎所有给出的答案都要求在访问感兴趣的属性中的值之前,将JSON完全反序列化为Java对象。另一种不走这条路的替代方法是使用JsonPATH,它类似于JSON的XPath,允许遍历JSON对象。

它是一个规范,JayWay的优秀人员已经为该规范创建了一个Java实现,您可以在这里找到:https://github.com/jayway/JsonPath

所以基本上要使用它,把它添加到你的项目中,例如:

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>${version}</version>
</dependency>

并使用:

String pageName = JsonPath.read(yourJsonString, "$.pageInfo.pageName");
String pagePic = JsonPath.read(yourJsonString, "$.pageInfo.pagePic");
String post_id = JsonPath.read(yourJsonString, "$.pagePosts[0].post_id");

等等……

查看JsonPath规范页面,了解横向JSON的其他方法的更多信息。

其他回答

Java中有许多可用的JSON库。

最臭名昭著的是:Jackson, GSON, Genson, FastJson和org.json。

在选择任何库时,通常应该注意以下三点:

性能 易于使用(代码写起来简单易读)——这与功能有关。 对于移动应用:依赖/jar大小

特别是对于JSON库(以及任何序列化/反序列化库),数据绑定通常也很有趣,因为它消除了编写样板代码来打包/解包数据的需要。

对于1,看到这个基准:https://github.com/fabienrenaud/java-json-benchmark我做了使用JMH比较(杰克逊,gson, genson, fastjson, org。使用stream和databind api实现序列化器和反序列化器的性能。 第二,你可以在网上找到很多例子。上面的基准测试也可以作为例子的来源。

快速总结一下基准:杰克逊的表现比组织好5到6倍。json,比GSON好两倍以上。

对于您的特定示例,下面的代码将使用jackson解码json:

public class MyObj {

    private PageInfo pageInfo;
    private List<Post> posts;

    static final class PageInfo {
        private String pageName;
        private String pagePic;
    }

    static final class Post {
        private String post_id;
        @JsonProperty("actor_id");
        private String actorId;
        @JsonProperty("picOfPersonWhoPosted")
        private String pictureOfPoster;
        @JsonProperty("nameOfPersonWhoPosted")
        private String nameOfPoster;
        private String likesCount;
        private List<String> comments;
        private String timeOfPost;
    }

    private static final ObjectMapper JACKSON = new ObjectMapper();
    public static void main(String[] args) throws IOException {
        MyObj o = JACKSON.readValue(args[0], MyObj.class); // assumes args[0] contains your json payload provided in your question.
    }
}

如果你有任何问题请告诉我。

目前有许多开源库可以将JSON内容解析为对象,或者仅用于读取JSON值。您的要求只是读取值并将其解析为自定义对象。所以org。Json库在你的情况下是足够的。

使用org。解析它并创建JsonObject:

JSONObject jsonObj = new JSONObject(<jsonStr>);

现在,使用这个对象来获取你的值:

String id = jsonObj.getString("pageInfo");

你可以在这里看到一个完整的例子:

如何在Java中解析JSON

您可以使用Gson库来解析JSON字符串。

Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(jsonAsString, JsonObject.class);

String pageName = jsonObject.getAsJsonObject("pageInfo").get("pageName").getAsString();
String pagePic = jsonObject.getAsJsonObject("pageInfo").get("pagePic").getAsString();
String postId = jsonObject.getAsJsonArray("posts").get(0).getAsJsonObject().get("post_id").getAsString();

你也可以循环"posts"数组,如下所示:

JsonArray posts = jsonObject.getAsJsonArray("posts");
for (JsonElement post : posts) {
  String postId = post.getAsJsonObject().get("post_id").getAsString();
  //do something
}
{
   "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"
         }
    ]
}

Java code :

JSONObject obj = new JSONObject(responsejsonobj);
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");
    ......etc
}

您可以使用JsonNode来表示JSON字符串的结构化树。它是无处不在的杰克逊图书馆的一部分。

ObjectMapper mapper = new ObjectMapper();
JsonNode yourObj = mapper.readTree("{\"k\":\"v\"}");