How to convert java object into a JSON?

In this article we show how to convert a java object into JSON. let’s Firstly discuss about object and JSON.

Object:

Java objects are the key to understand the object-oriented programming approach. An object consists of a state and behavior. The state of an object is one of the possible conditions that an object can exist in. And is also represented by its characteristics or attribute or data. However, The behavior of an object determines how an object behaves.

JSON:

JSON stands for JavaScript Object Notation. It is a lightweight format storing and transporting data. Json often uses it when we send the data from a server to a web page.

There are two methods as follows

  • GSON
  • Jackson API

Jackson API:

This example shows how to use JACKSON API to convert a Java Object into a JSON String.

We can use the ObjectMapper class provided by the Jackson API for our conversion.

  • writeValueAsString() this method, used to convert java obj to JSON
  • readValue() this method, used to convert JSON into java obj
1.Add jar files of Jackson(in case of MAVEN project add jackson dependencies in pom.xml file)
<dependency>
       <groupId>com.fasterxml.jackson.core</groupId>
       <artifactId>jackson-databind</artifactId>
       <version>2.10.2</version>
</dependency>
2. Use the Jackson API ObjectMapper class to convert Java Object to a JSON string
ObjectMapper mapper = new ObjectMapper();
try {
  String json = mapper.writeValueAsString(cat);
  System.out.println("ResultingJSONstring = " + json);
  //System.out.println(json);
} catch (JsonProcessingException e) {
   e.printStackTrace();
}

For Example:

class useJACKSONapiToConvertJavaOBJtoJSONstring

import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.databind.ObjectMapper;
 public class useJACKSONapiToConvertJavaOBJtoJSONstring {
     public static void main(String[] args) {
        dog dog = new dog();
         dog.setId(1L);
         dog.setName("Rio");
         dog.setColor("white");
         dog.setEyecolor("Black"); 
         dog.setBreed("pomeranian");                
         ObjectMapper mapper = new ObjectMapper();
         try {
             String json = mapper.writeValueAsString(cat);
             System.out.println("ResultingJSONstring = " + json);
             //System.out.println(json);
         } catch (JsonProcessingException e) {
             e.printStackTrace();
 }
 class Dog
public class Dog {
     private Long id; 
     private String name;
     private String color;
     private String eyecolor;
     private String breed;     
     public Dog() {
     public Dog(Long id, String name) {
         this.id = id;
         this.name = name;     
     // Getters & Setters  
     @Override
     public String toString() {
         return "Dog{" +
             "id=" + id +
             ", name='" + name +            
             '\'' +
             '}';
 public Long getId() { return id; }
 public void setId(Long id) { this.id = id; }
 public String getName() { return name; }
 public void setName(String name) { this.name = name; }
 public String getColor() {  return color; }
 public void setColor(String color) { this.color = color; }
 public String getEyecolor() { return eyecolor;
 public void setEyecolor(String eyecolor) { this.eyecolor = eyecolor; }
 public String getBreed() {  return breed; }
 public void setBreed(String breed) { this.breed = breed; }
 } 

AS a Result:


ResultingJSONstring = {"id":1,
                       "name":"Rio",
                       "color":"White",
                       "eyecolor":"black",
                       "breed":"pomeranian"
}


GSON

The Google GSON library is the most used for converting Java objects into JSON.
The steps to do this as shown below.

  1. Include the GSON JAR files into your classpath (In case of MAVEN project add GSON dependencies in pom.xml file)
<dependency> 
       <groupId>com.google.code.gson</groupId> 
       <artifactId>gson</artifactId> 
       <version>2.6.2</version> 
   </dependency> 

2. Create class UseGSONNapito Convert Java OBject To JSON String

Call the GSON API using gson = new Gson();

For example

import com.google.gson.Gson; 
public class UseGSONapitoConvertJavaOBJtoJASONstring{ 
  public static void main(String args[]) { 
   DogDetails user = new DogDetails("Rio",      
           "pomeranian",
          "Rio.dog@gmail.com",
           9,
           2129991234L,
           "NewDogadonia",
           true);            
    Gson gson = new Gson();    
    String json = gson.toJson(user);
    System.out.println(json);   
}

Class DogDetails:

/**
 * Java Program to map a Java object to JSON String using GSON library. 
 */
class DogDetails {
  private String name;  
  private String breed;
  private String email;
  private int doglives;
  private long phone;
  private String city;
  private boolean likesMice; 
 
  public DogDetails(String name, String breed, String email, int doglives, long phone,
      String city, boolean likesMice) {
    super();
    this.name = name;
    this.email = email;
    this.doglives = doglives;
    this.phone = phone;
    this.city = city;
    this.likesMice = likesMice;    
    this.breed = breed;
//getters & setters
public String getName() {
  return name;
}
public void setName(String name) {
  this.name = name;
}
public String getBreed() {
  return breed;
}
public void setBreed(String breed) {
  this.breed = breed;
}
public String getEmail() {
  return email;
}
public void setEmail(String email) {
  this.email = email;
}
public int getDoglives() {
  return doglives;
}
public void setDoglives(int dogtlives) {
  this.doglives = doglives;
}
public long getPhone() {
  return phone;
}
public void setPhone(long phone) {
  this.phone = phone;
}
public String getCity() {
  return city;
}
 
public void setCity(String city) {
  this.city = city;
}
public boolean isLikesMice() {
  return likesMice;
}
public void setLikesMice(boolean likesMice) {
  this.likesMice = likesMice;
}
}

3. RUN UseGSONapitoConvertJavaOBJtoJASONstring

As a Result:

{
"name":"Rio",
"breed":"pomeranian",
"email":"rio.dog@gmail.com",
"doglives":9,
"phone":2129991234,
"city":"NewCatadonia",
"likesMice":true
}

Recommended Post:

Difference between the Java and JavaScript

What is JavaScript?

How are java objects stored in memory?

Compilation and Execution of a java program

Reference:

www.geeksforgeerks.org

blog.codeta.com

Leave a Reply

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