我有以下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"
    }
  ]
}

当前回答

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处理实现一样对待。

其他回答

如果你有一些Java类(比如Message)表示JSON字符串(jsonString),你可以使用Jackson JSON库:

Message message= new ObjectMapper().readValue(jsonString, Message.class);

你可以从message对象中获取它的任何属性。

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

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

JSONObject jsonObj = new JSONObject(<jsonStr>);

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

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

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

如何在Java中解析JSON

{
   "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
}

为了便于示例,让我们假设您有一个只有名称的Person类。

private class Person {
    public String name;

    public Person(String name) {
        this.name = name;
    }
}

谷歌GSON (Maven)

我个人最喜欢的JSON对象序列化/反序列化。

Gson g = new Gson();

Person person = g.fromJson("{\"name\": \"John\"}", Person.class);
System.out.println(person.name); //John

System.out.println(g.toJson(person)); // {"name":"John"}

更新

如果你想获取单个属性,你可以很容易地使用谷歌库:

JsonObject jsonObject = new JsonParser().parse("{\"name\": \"John\"}").getAsJsonObject();

System.out.println(jsonObject.get("name").getAsString()); //John

Org。JSON (Maven)

如果您不需要对象反序列化,而只是获得一个属性,您可以尝试org。json(或查看上面的GSON示例!)

JSONObject obj = new JSONObject("{\"name\": \"John\"}");

System.out.println(obj.getString("name")); //John

杰克逊(Maven)

ObjectMapper mapper = new ObjectMapper();
Person user = mapper.readValue("{\"name\": \"John\"}", Person.class);

System.out.println(user.name); //John

你可以使用Jayway JsonPath。下面是一个GitHub链接,包括源代码、pom细节和良好的文档。

https://github.com/jayway/JsonPath

请按照以下步骤操作。

步骤1:使用Maven在类路径中添加jayway JSON路径依赖项,或者下载JAR文件并手动添加它。

<dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <version>2.2.0</version>
</dependency>

步骤2:请将输入的JSON保存为本示例的文件。在我的情况下,我将JSON保存为sampleJson.txt。注意,pageInfo和posts之间没有逗号。

步骤3:使用bufferedReader从上面的文件中读取JSON内容,并将其保存为String。

BufferedReader br = new BufferedReader(new FileReader("D:\\sampleJson.txt"));

StringBuilder sb = new StringBuilder();
String line = br.readLine();

while (line != null) {
    sb.append(line);
    sb.append(System.lineSeparator());
    line = br.readLine();
}
br.close();
String jsonInput = sb.toString();

步骤4:使用jayway JSON解析器解析JSON字符串。

Object document = Configuration.defaultConfiguration().jsonProvider().parse(jsonInput);

第五步:像下面这样阅读细节。

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

System.out.println("$.pageInfo.pageName " + pageName);
System.out.println("$.pageInfo.pagePic " + pagePic);
System.out.println("$.posts[0].post_id " + post_id);

输出将是:

$.pageInfo.pageName = abc
$.pageInfo.pagePic = http://example.com/content.jpg
$.posts[0].post_id  = 123456789012_123456789012