How to convert a Java object to JSON

JavaScript Object Notation (JSON) is a light-weight data storage format for storing and transmitting data. It is stored in the form of key-value pairs.

There are two main methods used to convert a Java object into a JSON:

  • GSON
  • Jackson API

GSON

The Google GSON​ library is the most popular library used for converting Java objects to JSON.

The code to get a JSON String out of an object is given below.

import com.google.gson.Gson;
public class main
{
public class Employee {
private String name;
private int age;
}
public static String convertUsingGson(Employee e)
{
Gson gson = new Gson();
String employeeJson = gson.toJson(e);
return employeeJson;
}
}

The GSON dependency library needs to be installed (first) ​in order to declare a Gson object.

Jackson API​

The ObjectMapper API in Jackson is used for data-binding. It comes with several reader/writer methods to perform​ the conversion to/from Java and JSON.

The code to get a JSON String out of an object is given below.

import java.io.File;
import com.fasterxml.jackson.databind.ObjectMapper;
public class main{
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
Employee emp = createEmployee();
try {
// Java objects to JSON string
String jsonString = mapper.writeValueAsString(emp);
System.out.println(jsonString);
} catch (IOException e) {
e.printStackTrace();
}
}
private static Employee createEmployee() {
Employee e = new Employee();
e.setName("Jon");
e.setAge(25);
return e;
}
}

The Jackson dependency library​ needs to be installed (first) ​in order to declare a Jackson/ObjectMapper object.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved