Java – How to parse JSON in Java

javajsonparsing

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

Best Answer

The org.json library is easy to use.

Just remember (while casting or using methods like getJSONObject and getJSONArray) that in JSON notation

  • [ … ] represents an array, so library will parse it to JSONArray
  • { … } represents an object, so library will parse it to JSONObject

Example code below:

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");
    ......
}

You may find more examples from: Parse JSON in Java

Downloadable jar: http://mvnrepository.com/artifact/org.json/json