我有以下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的其他方法的更多信息。

其他回答

The below example shows how to read the text in the question, represented as the "jsonText" variable. This solution uses the Java EE7 javax.json API (which is mentioned in some of the other answers). The reason I've added it as a separate answer is that the following code shows how to actually access some of the values shown in the question. An implementation of the javax.json API would be required to make this code run. The full package for each of the classes required was included as I didn't want to declare "import" statements.

javax.json.JsonReader jr = 
    javax.json.Json.createReader(new StringReader(jsonText));
javax.json.JsonObject jo = jr.readObject();

//Read the page info.
javax.json.JsonObject pageInfo = jo.getJsonObject("pageInfo");
System.out.println(pageInfo.getString("pageName"));

//Read the posts.
javax.json.JsonArray posts = jo.getJsonArray("posts");
//Read the first post.
javax.json.JsonObject post = posts.getJsonObject(0);
//Read the post_id field.
String postId = post.getString("post_id");

现在,在大家对这个答案投反对票之前因为它没有使用GSON, org。json, Jackson或任何其他可用的第三方框架,它是每个问题解析所提供文本的“所需代码”的示例。我很清楚JDK 9没有考虑遵守当前标准JSR 353,因此JSR 353规范应该与任何其他第三方JSON处理实现一样对待。

Jsoniter (jsoniterator)是一个相对较新的和简单的json库,旨在简单和快速。反序列化json数据所需要做的就是

JsonIterator.deserialize(jsonData, int[].class);

其中jsonData是json数据的字符串。

去官方网站看看吧 获取更多信息。

这让我惊讶于它是多么简单。你可以在默认的组织中传递一个包含JSON的String给JSONObject的构造函数。json包。

JSONArray rootOfPage =  new JSONArray(JSONString);

完成了。滴麦克风。 这也适用于JSONObjects。在此之后,您可以使用对象上的get()方法查看对象的层次结构。

Quick-json解析器非常简单,灵活,快速,可定制。试一试

特点:

Compliant with JSON specification (RFC4627) High-Performance JSON parser Supports Flexible/Configurable parsing approach Configurable validation of key/value pairs of any JSON Hierarchy Easy to use # Very small footprint Raises developer friendly and easy to trace exceptions Pluggable Custom Validation support - Keys/Values can be validated by configuring custom validators as and when encountered Validating and Non-Validating parser support Support for two types of configuration (JSON/XML) for using quick-JSON validating parser Requires JDK 1.5 No dependency on external libraries Support for JSON Generation through object serialisation Support for collection type selection during parsing process

它可以这样使用:

JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonMap=parser.parseJson(jsonString);

Jakarta (Java)企业版8包含JSON- b(用于JSON绑定的Java API)。因此,如果您使用的是Jakarta EE 8服务器,如Payara 5, JSON-B将是开箱即用的。

一个简单的例子,没有自定义配置:

public static class Dog {
    public String name;
    public int age;
    public boolean bites;
}

// Create a dog instance
Dog dog = new Dog();
dog.name = "Falco";
dog.age = 4;
dog.bites = false;

// Create Jsonb and serialize
Jsonb jsonb = JsonbBuilder.create();
String result = jsonb.toJson(dog);

// Deserialize back
dog = jsonb.fromJson("{\"name\":\"Falco\",\"age\":4,\"bites\":false}", Dog.class);

您可以使用配置、注释、适配器和(反)序列化器自定义映射。

如果你没有使用Jakarta EE 8,可以随时安装JSON-B。