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

当前回答

您可以使用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
}

其他回答

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。

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

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

任何类型的json数组 解决问题的步骤。

将JSON对象转换为java对象。 你可以使用这个链接或任何在线工具。 保存为java类,如Myclass.java。 Myclass obj = new Gson().fromJson(JsonStr, Myclass.class); 使用obj,你可以得到你的值。

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

为了便于示例,让我们假设您有一个只有名称的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