This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

This article, the original problem: translate for stackoverflow question stackoverflow.com/questions/2…

Issue an overview

How can I parse pageName, pagePic, post_id, etc?

    {
       "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"}}]Copy the code

Best answer

The org.json package is easy to use. Just remember the JSON representation (when calling methods like getJSONObject and getJSONArray). […]. Represents an array, so use JSONArray {… } represents an object, so JSONObject

import org.json.*;

String jsonString = ... ; //assign your JSON String here
JSONObject obj = new JSONObject(jsonString);
String pageName = obj.getJSONObject("pageInfo").getString("pageName");

JSONArray arr = obj.getJSONArray("posts"); // notice that `"posts": [...] `
for (int i = 0; i < arr.length(); i++)
{
    String post_id = arr.getJSONObject(i).getString("post_id"); . }Copy the code

More examples can be found at theoryapp.com/parse-json-…

Downloadable jar: mvnrepository.com/artifact/or…

Other answer

You need to create a class that looks like this

private class Person {
    public String name;

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

Then, I recommend GSON, serialization and deserialization are easy

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"}
Copy the code

It is also easy to export only one property

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

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

JSON. If you don’t need JSON serialization, you can use this. Just read the answer above

And then Jackson

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

System.out.println(user.name); //John
Copy the code