Categories
java json parsing

How to parse JSON in Java

1257

I have the following JSON text. How can I parse it to get the values of 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"
             }
        ]
    }

9

  • 2

  • 11

    java’s built in JSON libraries are the quickets way to do so, but in my experience GSON is the best library for parsing a JSON into a POJO painlessly.

    Mar 9, 2016 at 11:11

  • 4

    There are many notorious java libraries in java: jackson, gson, org.json, genson, etc. Choosing one should take into account their relative performance and feature set. Here is a benchmark did using JMH that compares the performance of the most popular json libraries in java: github.com/fabienrenaud/java-json-benchmark. See my post below for some more info.

    – fabien

    Jun 27, 2016 at 20:35


  • 7

    @JaysonMinard agreed. Asked for mod intervention. This should be closed really. I initially assumed (wrongly) I couldn’t do so while the question was protected, so I unprotected it and did my thing. Re-protected it now to prevent low rep answers and such like, while waiting for a mod.

    – Mena

    Jan 31, 2018 at 16:59

  • 7

    This question is being discussed on Meta.

    Feb 5, 2018 at 12:34

636

For the sake of the example lets assume you have a class Person with just a name.

private class Person {
    public String name;

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

Google GSON (Maven)

My personal favourite as to the great JSON serialisation / de-serialisation of objects.

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

Update

If you want to get a single attribute out you can do it easily with the Google library as well:

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

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

Org.JSON (Maven)

If you don’t need object de-serialisation but to simply get an attribute, you can try org.json (or look GSON example above!)

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

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

Jackson (Maven)

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

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

10

  • 21

    Good answer. One suggestion for minor improvement: both GSON and Jackson also support use of JSON tree representation (for Jackson these are JsonNodes, GSON has something similar). Might be good to show snippets, since that is similar to the only way org.json offers.

    – StaxMan

    Oct 6, 2015 at 18:05

  • Two other libraries worth mentioning (in the interest of completeness): json-simple and Oracle’s JSONP

    Apr 1, 2016 at 19:04


  • 5

    @NeonWarge, why? It seems to me that this answer assumes one has already defined a Java class that contains exactly the same fields as the JSON string, nothing less and nothing more. This is quite a strong assumption.

    Apr 9, 2016 at 20:40

  • 3

    json-simple and oracle’s jsonp perform terribly: github.com/fabienrenaud/java-json-benchmark For performance, choose jackson or dsljson.

    – fabien

    Aug 1, 2016 at 1:04


  • GSON does not support dynamic filtering of fields on levels other than root!

    – Gangnus

    Aug 6, 2016 at 14:02

112

  1. If one wants to create Java object from JSON and vice versa, use GSON or JACKSON third party jars etc.

    //from object to JSON 
    Gson gson = new Gson();
    gson.toJson(yourObject);
    
    // from JSON to object 
    yourObject o = gson.fromJson(JSONString,yourObject.class);
    
  2. But if one just want to parse a JSON string and get some values, (OR create a JSON string from scratch to send over wire) just use JaveEE jar which contains JsonReader, JsonArray, JsonObject etc. You may want to download the implementation of that spec like javax.json. With these two jars I am able to parse the json and use the values.

    These APIs actually follow the DOM/SAX parsing model of XML.

    Response response = request.get(); // REST call 
        JsonReader jsonReader = Json.createReader(new StringReader(response.readEntity(String.class)));
        JsonArray jsonArray = jsonReader.readArray();
        ListIterator l = jsonArray.listIterator();
        while ( l.hasNext() ) {
              JsonObject j = (JsonObject)l.next();
              JsonObject ciAttr = j.getJsonObject("ciAttributes");
    

3

  • 4

    @nondescript If I had to guess I’d say it was downvoted because it doesn’t answer the original poster’s question: “What is the required code?” The answers that were upvoted provided code snippets.

    Apr 27, 2015 at 21:40


  • 4

    Note: Jackson and GSON both support tree-style and/or Maps/Lists binding, so there is no need to use Java EE (javax.json) package. javax.json has little to offer beyond either Jackson or GSON.

    – StaxMan

    Jun 1, 2015 at 23:10

  • I suggest adding a link to the JavaEE library.

    May 26, 2018 at 6:25