Javatpoint Logo
Javatpoint Logo

Convert Java Object to Json using GSON

JSON stands for JavaScript object notation, is a lightweight format for storing and transporting the data. It stores the data as the key-value pair. Most of the applications use this format for transmitting the data from the server to the web page, or vice-versa. However, we must convert the java object to JSON string to transmit it over the network. In Java, we can use the following methods to convert a Java object to Json.

  1. GSON: It is a java library that contains methods to serialize and deserialize Java objects to JSON. It is open-source.
  2. Jackson API

In this tutorial, we will convert the Java object to JSON using the GSON library. Consider the following steps to convert the Java object to JSON.

1. Create a maven project in eclipse and use pom.xml to add GSON dependencies.

2. Create a Plain Old Java Object (POJO) that is to be converted into Json. Consider the following java code to create the java object.

3. Create a java class that uses Gson class to convert the Company object to Json.

4. We will get the JSON object upon executing the ConvertJSON class. The generated JSON string is given below.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA