You are here
Home > java >

How To Convert Java Object To JSON?

Convert Java Object To JSONAlmost every Java developer come across the word ‘JSON’ during project development. In fact, not only the Java developer, but also other language developers, even UI developers. Almost everyone in the software industry directly or indirectly, sooner or later get a chance to work with JSON. Now you can imagine how important it is to know in & out of it. You may have a question in your mind ‘ How to convert Java Object to JSON’ and ‘How to convert JSON to Java Object?’.

Although JSON syntax is very easy to write, but sometimes it creates confusion when an object is a bit complex. You must require knowledge of it when you test your application by sending or receiving JSON data. Moreover, it also becomes important while resolving the data format error. In this article, we will do enough practice with clear & concise concepts to become expert in handling any format of JSON data. Let’s get into our topic ‘Java Object To JSON’.

What will you learn from this article?

After going through the complete article you will learn about :

1) What is JSON and how to represent it?
2) Where do we use the JSON & Why ?
3) How to represent JSON in case of Java Objects like in List, Set, Map, Properties, Arrays etc.?
4) Additionally How to represent a complex Java Object To JSON String ?
5) How to test REST applications when passing JSON string and getting Java Objects and vice versa?
6) Then, How to convert Java Object to JSON and JSON to Java Object programmatically?
7) As a Java developer that’s enough to answer ‘What is Java JSON’ and ‘How to work with JSON in Java?’

What is JSON ?

JSON is a lightweight data syntax of storing, transferring & exchanging data. It stands for JavaScript Object Notation. It is related to JavaScript in that it utilizes a syntax that is more or less similar to a subset of JavaScript literals. A JSON object contains data in the form of key-value pair just like Properties file or Map in Java but has different syntax. One pair of key and value is called an entry. Each entry is separated by comma. The key must be quoted(” “), value is quoted only if type is String. For example:

{ "id" : 10, "name": "Mary", "salary" : 3775.6 } 
♦ One { } (curly brace) indicates one Object.

What is Java JSON?

Java JSON refers to the handling and processing of JSON (JavaScript Object Notation) data within the Java programming language. Let’s assume that we have a class Employee as below:

public class Employee {

   Integer eId;
   String eName;
   Double eSal;

   public Employee(Integer eId, String eName, Double eSal) {
      this.eId = eId;
      this.eName = eName;
      this.eSal = eSal;
   }
}

If we create an object of Employee as below:

Employee e = new Employee(137229,"Robert",80755.0);

Above data can be written in JSON as below:

{ "eId": 137229, "eName": "Robert", "eSal":80755.0 }

It should clear the concept of ‘What is Java JSON’. If you need more information on JSON, kindly visit json website.

What is JSON format?

JSON comes with a conventional text-based format for representing structured data. It is similar to the JavaScript object syntax. Commonly we use it for transmitting data in web applications from server to client and vice versa. It has a nominal number of value types such as strings, numbers, Booleans, lists, objects, and null. Although these types are available in all common programming languages which makes JSON a good contestant to transmit data across all languages.

Where is JSON representation used?

JSON will be used in places where we need small data storage, data transfer & data exchange. However, we, as a java developer use it in Webservices most of the times. It is the most popular format of data used in REST webservices. Even Spring Boot REST API supports JSON format by default. Moreover, if you want to use xml format, you will have to provide additional configurations while working with Spring Boot REST. JSON is lightweight and universally accepted format to store, transfer & exchange data. Even Mongo DB stores data in the form of JSON. So it is very important to clear your concepts of JSON before working with Mongo DB as well.

Sometimes one application interacts with another application irrespective of the programming/scripting languages they are written in. In this case, we need a common format of data to establish communication between them so that each application can understand it easily. JSON becomes the best choice in this scenario as it is language-independent. Needless to say that this type of communication generally happens in webservices concept.

How to represent List/Set/Array as a Java Object To JSON?

Let’s have a clear picture on ‘What is Java JSON?’.

JSON stores List, Set & Array Objects of Java as an Array only.
JSON Syntax will be as below (variable name as a key and values within [ ] separated by comma). For example:

"key": [ val1, val2, val3, val4....... ]

Note : You are advised to use at least JDK 9 to execute examples of this article, or modify your code accordingly. We will use of() method in order to initialize the collections in many places that was introduced in JDK 9.

For example, let’s consider a class Student as below :

class Student {

    Integer id;
    Set<String> subjects;
    List<Integer> marks;
    String[] grades;

    public Student(Integer id, Set<String> subjects, List<Integer> marks, String[] grades) {
       this.id = id;
       this.subjects = subjects;
       this.marks = marks;
       this.grades = grades;
    }
}
Java Object Representation:
Student s = new Student(
        500, 
        Set.of("Physics","Chemistry","Mathematics"),
        List.of(84,65,90),
        new String[]{"B","C","A"}
);
JSON Representation: 
Java Object vs JSON
 {
"sid" : 500,
"subjects" : [ "Physics","Chemistry","Mathematics" ],
"marks" : [ 84,65,90 ],
"grades" : ["B","C","A" ]
}

How to represent Map/Properties as a Java Object To JSON?

JSON stores Map, Properties of Java as an Object only (i.e. Within the curly brace {} with key-value pair).

For example, consider below Student class with a Map variable.

public class Student {

    Integer id;
    Map<String,Integer> marks;

    public Student(Integer id, Map<String, Integer> marks) {
       this.id = id;
       this.marks = marks;
    }
}

Java Object Representation:

Student s = new Student(346, Map.of("Physics",84,"Chemistry",65,"Mathematics",90));

JSON Format Representation:

Java Object vs JSON
{
"sid" : 346,
"marks" : {
"Physics" : 84,
"Chemistry" : 65,
"Mathematics" : 90
}

}

How to represent JSON if Java class has a ‘HAS-A’ relationship(Association Mapping)?

However, JSON stores objects as a ‘HAS-A’ relationship like one object containing another object. For example, consider we have One Student class with Address class as ‘HAS-A’ variable as below.

public class Student {

   Integer id;
   Map<String,Integer> marks;
   Address address;

   public Student(Integer id, Map<String, Integer> marks, Address address) {

      this.id = id;
      this.marks = marks;
      this.address = address;
   }
}


public class Address {

   Integer houseNo;
   String streetName;
   String countryName;

   public Address(Integer houseNo, String streetName, String countryName) {

      this.houseNo = houseNo;
      this.streetName = streetName;
      this.countryName = countryName;
   }
}
Java Object Representation:
Student s = new Student(
         346,
         Map.of("Physics",84,"Chemistry",65,"Mathematics",90),
         new Address(124, "Main Street", "Canada")
);
JSON Format Representation:
Java Object Vs JSON
{
"sid" : 346,
"marks" : {
"Physics" : 84,
"Chemistry" : 65,
"Mathematics" : 90
}
"address" : {
"houseNo" : 124,
"sreetName" : "Main Street",
"countryName" : "Canada"
}

}

How to represent a Complex JSON data?

After going through ‘What is Java JSON’, If you are clear with all above explained JSON data representations as of now, You can easily create JSON representation of a complex structure of data. Let’s create a complex JSON representation. Let’s assume that we have a student class with three variables Integer, Map & a List of Object Address. Address class has 4 variables in which 3 are primitives and one variable with ‘HAS-A’ relationship called House. House class again has 3 primitive variables. For example, observe the below code:

public class Student {

   Integer id;
   Map<String,Integer> marks;
   List<Address> addresses;

   public Student(Integer id, Map<String, Integer> marks, List<Address> addresses) {

      this.id = id;
      this.marks = marks;
      this.addresses = addresses;
   }
}


public class Address {

   String addrType;
   Integer houseNo;
   String streetName;
   String countryName;
   
   House house;

   public Address(String addrType, Integer houseNo, String streetName, String countryName, House house) {

       this.addrType = addrType;
       this.houseNo = houseNo;
       this.streetName = streetName;
       this.countryName = countryName;
       this.house = house;
   }
}


public class House {

   Integer noOfRooms;
   String houseType;
   Integer noOfWindows;

   public House(Integer noOfRooms, String houseType, Integer noOfWindows) {
      this.noOfRooms = noOfRooms;
      this.houseType = houseType;
      this.noOfWindows = noOfWindows;
   }
}
Java Object Representation:
Student s = new Student(

                346,
                Map.of("Physics",84,
                       "Chemistry",65,
                       "Mathematics",90),
                List.of(new Address("Present Address",
                                     124, 
                                    "Main Street",
                                    "Canada",
                                     new House(3,"Flat",2) 
                                    ),
                        new Address("Permanent Address",
                                     344, 
                                    "Loyal Street", 
                                    "United Kingdom",
                                     new House(5,"Row House",3)
                                    )
                        )
                );


JSON Format Representation:
Java Objects vs JSON
{
"sid" : 346,
"marks" : {
"Physics" : 84,
"Chemistry" : 65,
"Mathematics" : 90
}
"addresses" :[
{
"addrType" : "Present Address",
"houseNo" : 124,
"sreetName" : "Main Street",
"countryName" : "Canada",
"house" : {
"noOfRooms" : 3,
"houseType" : "Flat",
"noOfWindows" : 2
}
},
{
"addrType" : "Permanent Address",
"houseNo" : 344,
"sreetName" : "Loyal Street",
"countryName" : "United Kingdom",
"house" : {
"noOfRooms" : 5,
"houseType" : "Row House",
"noOfWindows" : 3
}
}
]
}

How to convert Java Objecs to JSON and JSON to Java Object programmatically?

Let’s discuss about conversions from Java Object to JSON and vice versa. In order to convert java object to JSON & vice versa, there are two APIs

1. Jackson API
2. GSON API

Here we will use the popular Jackson API. It provides ObjectMapper class to do conversions. In order to perform the conversions, we will use below methods.

writeValueAsString() : converts java object to JSON
readValue() : converts JSON to java Object

♦ Note on Required jars : If you are using Spring Boot Web Project, no dependency needs to be added. In other cases, you will need to add Jackson jars in your class path. For example, we have two classes in below code snippet : JSONUtil.java and one Person.java to test the results. You can use conversion methods of JSONUtil.java accordingly in your project as Utility methods.

Person.java

public class Person {

      String name;
      Integer age;
      String profession;

      public String getName() {
         return name;
      }
      public void setName(String name) {
         this.name = name;
      }
      public Integer getAge() {
         return age;
      }
      public void setAge(Integer age) {
         this.age = age;
      }
      public String getProfession() {
         return profession;
      }
      public void setProfession(String profession) {
         this.profession = profession;
      }

      @Override
      public String toString() {
         return "Person [name=" + name + ", age=" + age + ", profession=" + profession + "]";
      }
}

JSONUtil.java

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JSONUtil {

      private static ObjectMapper mapper;

      static {
         mapper= new ObjectMapper();
      }

      public static String convertJavaToJson(Object obj) {
         String resultAsJSON= "";
         try {
             resultAsJSON= mapper.writeValueAsString(obj);
         } catch (JsonProcessingException e) {
             e.printStackTrace();
         }
         return resultAsJSON;
      }

      public static <T> T convertJsonToJava(String jsonString, Class<T> cls) {
         T resultAsJavaObject = null;
         try {
             resultAsJavaObject= mapper.readValue(jsonString, cls);
         } catch (JsonProcessingException e) {
             e.printStackTrace();
         }
         return resultAsJavaObject;
      }

      public static void main(String[] args) {
         
         // Person Object As JSON
         Person p1 = new Person();
         p1.setName("Albert");
         p1.setAge(38);
         p1.setProfession("DBA");
         String personAsJSON= convertJavaToJson(p1);
         System.out.println("Person Object As JSON : " +personAsJSON);

         //JSON as Person Object
         Person p2= convertJsonToJava(personAsJSON,Person.class);
         System.out.println("JSON as Person Object : " +p2);
      }
}

Output

Person Object As JSON : {"name":"Albert","age":38,"profession":"DBA"}
JSON as Person Object : Person [name=Albert, age=38, profession=DBA]

Till now, apart from being familiar with ‘What is Java JSON’, you might have got a clear idea on ‘How to convert Java Object To JSON and vice versa?’. Now let’s check some frequently asked questions about this.

FAQ

Why do we use JSON in Java?

There are several reasons for using JSON in Java:

1) Easy to read and write: JSON is a human-readable format, and it is easy to read and write for both machines and humans.

2) Lightweight: JSON is a lightweight format, which means it requires less bandwidth and storage space compared to other formats like XML.

3) Platform-independent: JSON is a platform-independent format, which means it can be used in any programming language and operating system.

4) Widely supported: JSON is a widely supported format, and there are many libraries available in Java that can be used to parse and generate JSON data.

5) Supports complex data types: JSON supports complex data types such as Arrays, List, Set, Map, Properties and Objects, making it a flexible and powerful format for data serialization.

Why JSON is used in Rest?

JSON is used in REST because it is a lightweight, human-readable, easy-to-parse, flexible, and widely supported format for data interchange. These characteristics make it an ideal choice for building RESTful web services that require fast and efficient data transfer over the network.

How can I parse JSON data in Java?

We can parse JSON data in Java using libraries like Jackson, Gson, or org.json. These libraries provide APIs for reading JSON data and converting it into Java objects. Additionally, to convert Java objects into JSON format, we can use JSON libraries such as Jackson, Gson, or org.json. These libraries offer methods to serialize Java objects into JSON strings.

Can you provide an example of parsing JSON data in Java using the Jackson library?

Below is a simplified example of parsing JSON using the Jackson library:

import com.fasterxml.jackson.databind.ObjectMapper;

String jsonString = "{\"name\":\"John\",\"age\":30}";
ObjectMapper objectMapper = new ObjectMapper();
Person person = objectMapper.readValue(jsonString, Person.class);

In this example, we parse a JSON string into a Person object.

What is the difference between Jackson, Gson, and org.json libraries for JSON handling in Java?

Jackson and Gson are common third-party libraries known for their robust JSON processing abilities. They offer advanced features like data binding and customization. org.json is a simple JSON library included in Java SE, but it lacks some of the advanced features of Jackson and Gson.

Conclusion

After going through all the theoretical & example part of ‘Convert Java Object To JSON’, we should be able to convert Java Object to JSON & vice versa in Java smoothly. Similarly, we expect from you to further extend these examples and implement them in your real project accordingly. Moreover, please feel free to provide your comments in the comments section below.

Further, if you want to go through other articles on latest concepts of Java published by us, kindly visit the blogs page.

7 thoughts on “How To Convert Java Object To JSON?

  1. We have already Restcontroller that converts entity class as a json response then could clarify in which situation we can use jakson api

    1. @Pratap : Jakson API has been illustrated here just to provide information that what code Spring Boot framework uses internally. Sometimes we come across a situation when we don’t use annotations. In that situation it becomes useful to know the internal details.

Leave a Reply


Top