Parsing JSON

Before we dig into how to parse JSON in Java, let’s first briefly understand what JSON is and what is java. First, Java is an object-oriented programming language. It can be used to develop desktop, android, and web applications. JSON is (Javascript Object Notation). It depends on a subset of Javascript.JSON is language-independent, text-based, and lightweight. It’s used for humans and machines to read and write; hence JSON is essential when transmitting data over the web.

JSON can have two structures:
1. Object – a collection of unordered zero or more name/value pairs
2. Arrays – an ordered collection /sequence of zero or values

We may ask ourselves, why do we need JSON? Alright, there are various advantages of using JSON. First, it is self-describing. What makes it self describing is its hierarchical structure that makes its code easily understood without much hassle. Secondly, its compactness in size is great. Large files in XML can be tiny when converted to JSON. Lastly, but not least, is its simplicity. It’s straight-forward to view or edit since it’s also supported online JSON tools.

We can parse Json In java using a variety of libraries. Let’s discuss the 3 most common Libraries to use.

  1. org.json
  2. Gson
  3. JSON PATH
  4. Jackson

Parse JSON in Java using org.json

Lets parse this JSON, its an example that shows how to retrieve values for name, and post_id.

{
    "pageInfo": {
            "pageName": "Homepage",     
    },
    "posts": [
            {
                "post_id": "123456789",
                "author_name": "Moses Njoroge",
                "post_title": "How to parse JSON in Java",  
            }
    ]
}

Steps:

Adding the Library as a dependency. You can download the jar org.json libary from Mvn Repository.

To add the Jar file to your project. Open the project. In our case, we are going to use the Netbeans IDE. Under the Libraries folder, right-click add choose on add jar/ file. Navigate to the location where the Jar is located and click ok.

Adding jar file

This will allow you using the below dependencies without any error.

import org.json.JSONArray;
import org.json.JSONObject;

Convert the JSON string to JSON object using jsonobject class.

JSONObject obj = new JSONObject(json);
String name = obj.getString("name");
int age = obj.getString("age");

Lastly we getJSONObject method.

JSONArray arr = obj.getJSONArray("posts");
  for (int i = 0; i < arr.length(); i++) {
   String post_id = arr.getJSONObject(i).getString("post_id");
            System.out.println(post_id);
    }

Below is the complete java code.

import org.json.JSONArray;
import org.json.JSONObject;

public class ParseJSONOrg {
    static String json = "";
    public static void main(String[] args) {
       JSONObject object = new JSONObject(json);
       String name = object.getString("name");
       
        System.out.println(name);

        JSONArray arr = object.getJSONArray("posts");
        for (int i = 0; i < arr.length(); i++) {
            String post_id = arr.getJSONObject(i).getString("post_id");
            System.out.println(post_id);
        }
    }
}

Parse JSON in Java using GSON

Gson is based on an open-source library developed by Google. It is simple and easy to use, which gives it an advantage over other methods. Since it is developed and maintained by Google, its performance is better. Download the GSON jar file from Marven Repository.

The GSON dependencies added include:

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

I will demonstrate how to convert a JSON string to JSON Object using two data types that are an integer and a string. To convert the JSON string, write:

Gson gson = new Gson();
User p = gson.fromJson(jsonString, User.class);

Where JSON is the JSON string, and User.class is the model class representing the Java object class. Similarly, converting the JSON Object back to JSON string is also simple. Just write the code below:

Gson gson = new Gson();
String str = gson.toJson(json);

Input:

JSON String : {
  "name": "mose",
  "enail": "mose@gmail.com",
  "phone": 123456789}

Output:

Java Object : User [name=Mose, email=mose@gmail.com, phone=12345670]
package ParseJSON;

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

public class ParseJSONGson 
{
    static String json = " ";
    public static void main(String[] args) 
    {
      JsonObject gson = new JsonParser().parse(json).getAsJsonObject();

        String name = gson.toJson(json);
        System.out.println(name);

        JsonArray arr = gson.getAsJsonArray("posts");
        for (int i = 0; i < arr.size(); i++) {
            String post_id = arr.get(i).getAsJsonObject().get("post_id").getAsString();
            System.out.println(post_id);
        } 
  } 
}

Parsing string to JSON using Jackson in Java

Jackson Library is one of the widely used JSON converters because of its fast speed. It can support the parsing of large JSON data such as the one used in streaming. Therefore, this library is memory friendly. Despite its efficiency, it only supports JDK 1.5 and above and does not support J2ME projects either. Therefore, it is suitable for developing large projects by developing web services and Android projects since it’s light-weight.

The first step is to add the dependency in your POM.xml. Just add the dependency in the pom.xml file, as shown below. If you are using IntelliJ IDEA, just select project structure from the file menu. Select the library, then click on the plus button and search for Jackson-xc.

<dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-xc</artifactId>
      <version>1.9.11</version>
</dependency>

I am going to use the Jackson library as our JSON string to JSON Object converter and vice versa.

User mose = new ObjectMapper().readValue(json, User.class);

Below code converts JSON string to JSON object.

Driver converter = new Driver();
String json = "{\n" +
       "    \"name\": \"Mose\",\n" +
       "    \"email\": \"mose@gmail.com\",\n" +
       "    \"phone\": 12345670}";
converter.fromJson(json);

Output

Java Object : User [name=Mose, email=mose@gmail.com, phone=12345670]

To parse JSON Object back to JSON string, just use the code below

//Object to JSON in String
ObjectMapper mapper = new ObjectMapper();
String jsonInString = mapper.writeValueAsString(user);

Parsing String to JSON using JSON-Simple in Java

This library is open source. It is small too and uses a small memory compared to other libraries. It is commonly therefore used in Android and J2ME projects. One of its best advantages is that it can support very old projects before JDK 1.2. It is simple to write the code and use it at the same time.

Just as the above steps, it’s crucial to start by adding the JSON dependency before you start using it. As described in the parsing string to JSON Object using Gson, follow the same procedure, and add this dependency. Or download it and add the JAR to the project as usual, then you’re ready to go.

To parse JSON string to JSON object just use the code below:

JSONParser parser = new JSONParser();
JSONObject json = (User.class) parser.parse(jsonString);

Here jsonString is the JSON string that you need to parse.

Given the same input as from the above same example, the output is still the same.

Parse JSON in Java Using JsonPATH

This method includes using an XPath for SON, which is JsonPATH. Once again, you need to download its dependency—Maven Repository. Now let’s have a look at how to pass the JSONPath.

Dependency:

import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.JsonPath;

public class ParseJSONPath {
    static String json = " ";
    public static void main(String[] args) {
        String name = JsonPath.read(json, "$.pageInfo.name");
        System.out.println(pagenameame);

        Integer posts = JsonPath.read(json, "$.posts.length()");

        for(int i=0; i < posts; i++) {
            String post_id = JsonPath.read(json, "$.posts[" + i + "].post_id");
            System.out.println(post_id);
        }
    }
}

Conclusion

From the above discussion, it’s evident that there are various ways to parse JSON in Java. We have seen some advantages of using one method over the other. Jackson library is the best of all the can be viewed as the best because it is mostly used in production codes due to its simplicity and memory efficiency, and it can parse huge amounts of data. This property gives it an advantage in building web services over other libraries. The JSON library also proves to be efficient in memory and widely supported. Lastly, all methods can get the job done. It only depends on your requirements as a developer or an organization.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *