How can I parse JSON in Java?

How can I parse JSON in Java?

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

Using org.json Library: This solution utilizes the org.json library, which provides simple JSON parsing capabilities. It’s a lightweight library and easy to use for basic JSON parsing needs. However, it lacks some advanced features and flexibility compared to other libraries like Jackson or Gson.

Using org.json Library example.
import org.json.JSONObject;

String json = "{\"pageInfo\":{\"pageName\":\"abc\",\"pagePic\":\"http://example.com/content.jpg\"}}";
JSONObject obj = new JSONObject(json);
String pageName = obj.getJSONObject("pageInfo").getString("pageName");
String pagePic = obj.getJSONObject("pageInfo").getString("pagePic");

Thanks Macy!

So , as you know Jackson is a popular JSON parsing library in the Java ecosystem. It provides comprehensive JSON processing capabilities and is highly efficient. Jackson is suitable for handling complex JSON structures and offers features like streaming API and data binding.

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

String json = "{\"pageInfo\":{\"pageName\":\"abc\",\"pagePic\":\"http://example.com/content.jpg\"}}";
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(json);
String pageName = rootNode.get("pageInfo").get("pageName").asText();
String pagePic = rootNode.get("pageInfo").get("pagePic").asText();

Gson is another widely used JSON parsing library developed by Google. It’s known for its simplicity and ease of use. Gson can handle both simple and complex JSON structures and provides features for custom serialization and deserialization.

Using Gson Library example.

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

String json = "{\"pageInfo\":{\"pageName\":\"abc\",\"pagePic\":\"http://example.com/content.jpg\"}}";
JsonObject obj = JsonParser.parseString(json).getAsJsonObject();
String pageName = obj.getAsJsonObject("pageInfo").get("pageName").getAsString();
String pagePic = obj.getAsJsonObject("pageInfo").get("pagePic").getAsString();