Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
JSON
2.1.
Code Implementation
2.1.1.
Output
2.2.
Explanation
3.
POJO
3.1.
Code Implementation
3.1.1.
Output
3.2.
Explanation
4.
Conversion from JSON to POJO
4.1.
Create JSON File
4.1.1.
Output
4.2.
Explanation
4.3.
Convert JSON File To Java Object
4.3.1.
Output
4.4.
Explanation
4.5.
Import Jackson Libraries
4.6.
Java Code to Convert JSON String to POJO
4.7.
Code implementation
4.7.1.
Output
5.
 Advantages of JSON
6.
Disadvantages of JSON
7.
Advantages of POJO
8.
Disadvantages of POJO
9.
Difference Between JSON and POJO
10.
Frequently Asked Questions
10.1.
What are some of the challenges you might encounter when converting a JSON file to POJO?
10.2.
How do you handle errors that occur during the conversion process?
10.3.
How to convert JSON to Java classes?
10.4.
How can you handle JSON data which contains duplicate values?
10.5.
How can you optimize JSON to POJO conversions?
11.
Conclusion
Last Updated: Mar 27, 2024
Medium

JSON to POJO

Author Vidhi Sareen
0 upvote
Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

Introduction

In this article, we are going to discuss JSON and POJO. We will even discuss how we can convert JSON to POJO. JSON, also known as JavaScript Object Notation, is a lightweight data transfer format that is simple to understand by both humans and machines. POJO, also known as Plain Old Java Object, is a Java class that does not extend or implement any specialized classes or interfaces to users. 

JSON to POJO

This article will discuss how we can convert a JSON to a Java Object.

JSON

JSON stands for JavaScript Object Notation. It is a lightweight format used for transporting or storing information. JSON is a data format used to convey data from a server to a web page. It may transfer data structures, such as objects or arrays, from one location to another. Therefore it is effortless to read and write from a JSON file. There are different features of JSON. They are straightforward to read and write, Self-explanatory, Can be modified easily, and many more. We can use JSON in cases requiring faster processing, where there needs to be present data in a well-structured format, and many more. Let's take an example for better understanding.

Code Implementation

{
   "name": "Ninja_1",
   "age": 25,
   "hobbies": ["reading", "writing"],
   "Education": {
       "degree": "Bachelor's",
       "Major": "Computer Science"
   }
}

Output

output

Explanation

In this example, there are four JSON objects. They are "name," "age," "hobbies," and "education." These values can have different types like strings, arrays, objects, integers etc.  

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

POJO

POJO stands for Plain Old Java Object. It is an ordinary Java Object which is not restricted by any specific restriction. The POJO file does not require any particular classpath. POJO is used nowadays because it is easy to read and modify.  

Let's take an example for better understanding.

Code Implementation

//First class
package com.example.demo;
import java.util.ArrayList;
public class student1 {

    public class Root {
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        public ArrayList < String > getHobbies() {
            return hobbies;
        }
        public void setHobbies(ArrayList < String > hobbies) {
            this.hobbies = hobbies;
        }
        public student2 getEducation() {
            return education;
        }
        public void setEducation(student2 education) {
            this.education = education;
        }
        public String name;
        public int age;
        public ArrayList < String > hobbies;
        public student2 education;
    }
}
//Second Class

package com.example.demo;
public class student2 {

    public String degree;
    public String major;
    public String getDegree() {
        return degree;
    }
    public void setDegree(String degree) {
        this.degree = degree;
    }
    public String getMajor() {
        return major;
    }
    public void setMajor(String major) {
        this.major = major;
    }
}

Output

output

Explanation

We have taken the above JSON file and converted it into Java Objects. Here they are formed in two separate classes. The first class consists of Root functions named ‘student 1’. They are like name, age, hobbies. The class is called another class which has education attributes and we have named it as student 2. We have used getter and setter to set and get the values of all the properties. We can now use this class anywhere in the code without having any worry about how properties will be accessed and modified.

Conversion from JSON to POJO

To convert JSON to POJO, we will use the ObjectMapper class, which has the readValue() method to convert JSON to POJO. 'ObjectMapper class is present in Jackson Library. It provides the functionality to convert JSON to Java objects (POJO) or vice versa. It converts JSON strings, files, or streams into Java. ObjectMapper has commonly used methods. These functions are:

  • readValue(): used to convert JSON strings and files into Java objects.
     
  • writeValue(): used to generate JSON strings or files from Java objects.
     
  • Configure (): used to configure date or time or to provide serialization.

 

Let's explain the step by step process to convert JSON to POJO. 

Create JSON File

Create a JSON file that shows a course duration of 3 months and also include a teacher involved in this course along with the price of the course.

Code Implementation
{
    "course_name": "Programming Foundation Course",
    "duration": "3",
    "teacher_name1":"Ninja_1",
    "teachers_email1":"Ninja_1@gmail.com",
    "teacher_name2":"Ninja_2",
    "teacher_email2":"Ninja_2@gmail.com",
    "price": "2000"
}

Output

output

Explanation

This is a JSON file that shows a course that has a duration of three months and has two instructors named "Ninja_1" and "Ninja_2". They have also added the names and email addresses. We have also mentioned the price of the course.

Convert JSON File To Java Object

Now, let's create a POJO class to map JSON files to Java objects. We are using getter and setter methods to do this.

public class Student {

    private String course_name;

    private int duration;
    private String teacher_name1;
    private String teacher_email1;
    private String teacher_name2;
    private String teacher_email2;
    private int price;

    public Student() {

    }

    public String getCourse_name() {
        return course_name;
    }

    public void setCourse_name(String course_name) {
        this.course_name = course_name;
    }

    public int getDuration() {
        return duration;
    }

    public void setDuration(int duration) {
        this.duration = duration;
    }

    public String getTeacher_name1() {
        return teacher_name1;
    }

    public void setTeacher_name1(String teacher_name1) {
        this.teacher_name1 = teacher_name1;
    }

    public String getTeacher_email1() {
        return teacher_email1;
    }

    public void setTeacher_email1(String teacher_email1) {
        this.teacher_email1 = teacher_email1;
    }

    public String getTeacher_name2() {
        return teacher_name2;
    }

    public void setTeacher_name2(String teacher_name2) {
        this.teacher_name2 = teacher_name2;
    }

    public String getTeacher_email2() {
        return teacher_email2;
    }

    public void setTeacher_email2(String teacher_email2) {
        this.teacher_email2 = teacher_email2;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }
};

Output

output

Explanation

We have Getter and Setter methods to get and set the values of the properties. In the student class we have used getter and setter for all properties. They will allow us to control how the properties are accessed and modified. Overall, using getters and setters is a good practice that can make your code more robust and maintainable.

Import Jackson Libraries

There are some Jackson packages that we need in this conversion. There are three packages that we used. They are:

  • Jackson-core: It is used to create an impact of the non-Jackson code to the version used.
     
  • Jackson-data-bind: you can use any version according to your need and use case. They are used to create an ObjectMapper class that is used to read a JSON to the root object.
     
  • Jackson-annotations: you can use any version according to your need and use case. They are used to add the JSON Property attribute.

Java Code to Convert JSON String to POJO

Now let’s Join your JSON file with the POJO file that we have created.

Code implementation

package com.example.demo;

//import necessary files

import java.io.File;
import java.io.IOException;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

//Import necessary dependency

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@SpringBootApplication

//created a DemoApplication class
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
        //created a ObjectMapper

        ObjectMapper mapper = new ObjectMapper();
        //added a try catch block to ensure that our application works smoothly.

        try {
            //print values

            Student student = mapper.readValue(new File("data/simple.json"), Student.class);
            System.out.println("Course Name: " + student.getCourse_name());
            System.out.println("Duration: " + student.getDuration());
            System.out.println("teacher name: " + student.getTeacher_name());
            System.out.println("teacher email: " + student.getTeacher_email());
            System.out.println("Price: " + student.getCourse_name());

        } catch (JsonParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Output

output

In this code, we had a main method that reads a JSON file and converts it to POJO. The JSON file contains information about the course, duration, price, and teachers. The ObjectMapper is used to convert the JSON file that we have created to a Java Object using the readValue() method. 

 Advantages of JSON

Below are the advantages of JSON

  • They are lightweight data interchange formats that are easy to read and write.
     
  • JSON is language independent which means that it supports all programming languages.
     
  • JSON data can be converted into objects easily.
     
  • JSON is easy to understand by humans because of its syntax.
     
  • It creates transmission between a client server and a web page.

Disadvantages of JSON

Below are the disadvantages of JSON

  • JSON does not support comments, so they are difficult to document.
     
  • JSON can be very dangerous if used with an untrusted server. 
     
  • JSON is less expressive and flexible.
     
  • JSON has limited data types that are not used for all use cases.
     
  • JSON is less secure.

Advantages of POJO

Below are the advantages of POJO

  • They don’t have special restrictions other than those by Java.
     
  • POJO helps in encapsulation.
     
  • POJO is flexible means that it can be used in many different use cases like web applications, desktop applications etc.
     
  • POJO uses Getter and Setter.
     
  • In POJO, the same component can be used ‘n’ number of times. 

Disadvantages of POJO

Below are the disadvantages of JSON

  • POJO can increase the complexity of the code if the data is large.
     
  • POJO does not provide a standard way to extend a data format.
     
  • POJO is not recommended in the case where data interchanges between different systems.
     
  • POJO requires manual mapping between objects and data structures.
     
  • POJO does not provide built-in support for serialization.

Difference Between JSON and POJO

Below is the table of difference between JSON and POJO

Features JSON POJO
Data Format Text based format with key value pairs Java objects with attributes and methods
Flexibility Limited flexibility Based on the user input data structure.
Performance Lightweight and fast Slower due to many java objects
Serialization Support built in serialization Requires manual mapping
Data Types Supports Limited number of data types Supports all java data types and custom classes
Documentation It does not support comments Supports comments and documentations

Frequently Asked Questions

What are some of the challenges you might encounter when converting a JSON file to POJO?

Some challenges you might face are that the JSON file may not match with the structure of POJO, the JSON file may contain irrelevant data, the JSON file is too big to process, or the JSON file may be encrypted or compressed..

How do you handle errors that occur during the conversion process?

You can use try and catch exceptions by giving relevant messages. You can use documentation or assistance support if you face an error. You can even debug your code to find the bug.

How to convert JSON to Java classes?

We can convert a JSON to Java Object using the readValue() method of ObjectMapper class, this method deserializes a JSON content from given JSON content String.

How can you handle JSON data which contains duplicate values?

If JSON data have duplicate values, you can handle it using the appropriate configuration setting in your chosen library. You can even preprocess your data before converting it to POJO.

How can you optimize JSON to POJO conversions?

There are many ways in which you can improve the performance of conversion. You can use Jackson or Gson library to process large data smoothly. You can use a minimum number of functions in the POJO class, improving performance.

Conclusion

JSON is a JavaScript object Notation, and POJO is Plain Old Java Object. The conversion from JSON to POJO is a common task in software development. The process involves different steps to convert JSON to POJO. They are very useful in Java applications. There are many tools and libraries used in this conversion process. The most famous libraries used are Jackson and Gson. They both have their advantages and disadvantages. You can use them according to the use cases. Conversion is also used in transferring data from one place to another. Since JSON and Java have been used in this conversion, it helps the developers create a robust and scalable application. 

To learn more about this topic, do check the link below-

 

You can find more informative articles or blogs on our platform. You can also practice more coding problems and prepare for interview questions from well-known companies on your platform, Coding Ninjas Studio.

Previous article
JSON introduction and Syntax
Next article
Difference Between package.json and package-lock.json Files
Live masterclass