2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

How to parse JSON in Java

JSON text that I need to parse to get pageName, pagePic, post_id, etc.

What is the required code?

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

The org.json library is easy to use. Example code below:

import org.json.*;


JSONObject obj = new JSONObject(" .... ");
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");
    ......
}

You may find extra examples from: Parse JSON in Java

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


Answer is