Register Login

Convert JSON string to Java object

Updated May 26, 2023

JSON is short for JavaSCript Object Notation, one of the most widely used data formats, which indicates an open text-based data-interchange format derived from JavaScript.

When users deploy Java web applications and work with RESTful web services, they must parse JSON strings to Java objects. There are standard approaches to converting a JSON string to a Java object, and users can pass the data in web applications in a standard format.

This article will discuss the methods available to users to convert a JSON string to a Java object for the convenience of developing a web application.

Parsing JSON strings can be easier using Java libraries that are efficient and reduce the size of the class files.

Users can use the Java libraries, which can parse a JSON string to a Java object:

Though users can parse a string of JSON into Java without using the libraries, it is less efficient. For this, users must use the JSON parser specification as reported by the ECMA International specification and go for it by clicking here.

Without falling into such complicated steps and procedures, which might also create a program with the wrong JSON string format and produce the wrong output. Thus, it is a much better option to use the Java libraries; mentioned above to handle such use cases.

Method 1: Using the Jackson library of Java

Users can efficiently parse JSON strings into Java objects using the Jackson library, which has a built-in ObjectMapper class.

This ObjectMapper class provides the readValue() method, which helps convert the JSON string into a Java object and accepts JSON as one of its parameters. Jackson Library is among the most prevalent and well-chosen since it can parse streaming JSON data.

Code Snippet:

class sample {
    String n;
    int s;
    boolean i;

    public String getting_Name() {
        return n;
    }

    public void setting_Name(String n) {
        this.n = n;
    }

    public int getting_Age() {
        return s;
    }

    public void setting_Age(int s) {
        this.s = s;
    }

    public boolean getting_Id() {
        return i;
    }

    public void setting_Id(boolean i) {
        this.i = i;
    }
}

To access the Java class, we have created a named "Sample" with setters and getters for its fields; we have to use the setters and getters. Setters and getters help retrieve and update values of the variables outside the encapsulating class.

Use this code to parse the JSON string to a Java object:

import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
String demo = ""
    {
        "Employee_name":"XYZ",
        "Employee_salary":51500,
        "Employee_Id":true
    }""";

try {
    sample x = mapper.readValue(demo, sample.class);
    System.out.println(x.n); 
    System.out.println(x.s); 
    System.out.println(x.i);
} catch (IOException e) {
    e.printStackTrace();
}

Lastly, users need to call the writeValueAsString() method from the mapper instance, and we have shown it as follows:

String new_string = mapper.writeValueAsString(x);
System.out.println(new_string);

Output:

Explanation:

In the first code snippet, we created a Java class "sample" and then used the variables n, a, and i to indicate the name, age, and ID of the sample employees.

Then we used the functions getting_Name, setting_Name(), getting_Age(), setting_Age(), getting_Id(), and setting_Id to retrieve and store the values in it.

Then in the second code snippet, we used the ObjectMapper class from Jackson to read and write the JSON string to and from POJOs.

Then, we used the readValue() method from the mapper instance to deserialize the JSON string from the given document into a given Java object.

We passed the string variable as the first parameter and the Java blueprint class as the second. Lastly, we used the writeValueAsString() method from the mapper instance to parse the JSON string.

Method 2: Using the Gson library

It is another widely used library from Java to convert the JSON string to Java object and vice versa. The Gson library fully supports Java generics, which is one of the significant benefits of Gson. Users can create a clearer program to parse JSON in Java objects using this Java library.

Code Snippet:

class sample {
    String n;
    int s;
    boolean i;
}

Then parse the JSON string as an instance that we have declared in the class sample:

import com.google.gson.Gson;

String demo = ""
    {
        "Employee_name":"XYZ",
        "Employee_salary":51500,
        "Employee_Id":true
    }""";

Gson x = new Gson();
sample y = x.fromJson(demo, sample.class);
System.out.println(y.n); 
System.out.println(y.s); 
System.out.println(y.i);

Lastly, we parse the Java object into JSON string using the toJson() method of the Gson library:

String new_string = g.toJson(y);
System.out.println(new_string);

Output:

Explanation:

In this example, we used the Gson library with fromJson() and toJson() methods. We first created a class "sample" and initialized the variables n, a, and i to indicate the name, age, and ID of the sample employees.

Then, we used the fromJson() method to convert the string to an object after importing the library com.google.gson.Gson. Then, lastly, we used toJson() method to parse the JSON string into a Java object.

Method 3: Using the JSON-Java library

The last method is the JSON-java library, a lightweight Java library that can convert a JSON string into a Java object and vice versa. In this example, we will not use any class instance and initialize the class variables, only use the object JSONObject instance.

Code Snippet:

import org.json.JSONObject;
String demo = ""
    {
        "Employee_name":"XYZ",
        "Employee_salary":51500,
        " Do_have_ID ":true
    }""";

JSONObject object = new JSONObject(demo);
System.out.println(object.getString("Employee_name")); 
System.out.println(object.getInt("Employee_salary"));
System.out.println(object.getBoolean("Do_have_ID"));

Lastly, we parse the JSONObject back into a Java object using the toString() method from the JSONObject instance.

String new_string = object.toString();
System.out.println(new_string);

Output:

Explanation:

In this example, we used the JSON-java library to parse a JSON string which does not need a Java class as the JSON object blueprint. Here, we used the JSONObject instance and passed the values of the object using the getString(), getInt(), and getBoolean() methods.

These methods help to get the instance field of type string, int, and Boolean. Lastly, we used the toString() to convert the JSONObject back to a String.

Conclusion:

In developing Java web applications, developers often use these methods to parse the JSON string into Java objects, which is standard practice. In this article, we talked about the three popular Java libraries that help to convert the JSON String into an object with Java efficiently.


×