If you are a Java or Android developer and learning JSON to support JSON format for your project and looking for a quick and simple way to convert your Java object into json format then you have come to the right place. In this article, I'll teach you how to convert a Java object to a JSON document using Google's Java library called Gson. This library allows you to convert both Java objects to JSON String and a JSON document to Java objects. So, let's first do some serialization. Serialization in the context of Gson means mapping a Java object to its JSON representation.
In the real world, the data can be really complex with lots of attributes and nested with composed object but for now, we'll start with a class which just contain few values attributes like String, int and boolean.
Let's first create that class and call it UserDetails. It contains essential details of a user e.g. name, email, age, phone, city and a boolean field hasCreditCard to indicate that he owns a credit card.
Let's see that class in action, it will look like following
This is our simple POJO (Plain old Java object) which we will convert into JSON format. I have committed constructor, getters, and setter for simplicity. Unlike many other frameworks, Gson also doesn't require a default, no-argument constructor.
Now, let's take a close look at this UserDetails class. If you look carefully, it got six attributes, out of those name, email, and the city is String objects, age is an integer that tells how old user is and the phone is a long value to accommodate both 8 digit and 10 digit numbers. It also has a boolean hasCreditCard field to indicate whether the user owns a credit card or not.
The task is now to convert this object to an equivalent JSON String which you can use it on your Android or Java application. If we keep the field names the same, we would expect such a JSON or a normal user which doesn't own a credit card
So let's see how we can do the conversion with Gson. First of all, we need to create a Java object for this user
In order to serialize this object into equivalent JSON String, we need a Gson object, this is similar to ObjectMapper class of Jackson Databind library, in case you have used it before and trying Gson now. If you have never used any JSON parsing libraries in Java, then just remember, we need a class from the Gson library which will convert our Java object to JSON.
Let's create the object of Gson class for now:
The good thing is that you don't need to pass any parameter to create an instance of Gson class, but it doesn't mean that you cannot configure this object, of course, you can configure the Gson object to suit your need by enabling disabling various configuration parameters, which we'll learn in future articles. For now, let's just focus on serializing a simple Java object to JSON.
Next, we need to call the toJSon() function of Gson and pass the UserDetails object to this method. This will return the JSON String you are looking after.
The json String will look like the following:
Even though String would not be as pretty-printed as this but just a single line, you can see that GSon has generated a properly formatted JSON document e.g. String values are properly enclosed within double quotes, while integer values had no wrapping.
There is a comma after every element as well. We didn't have to do anything special, we just call the toJson() method of Gson class and boom, you have your JSON document ready. A single call to Gson was enough to map the entire object. This comes in extremely handy when we're working with a complex data structure.
You can also run this program in Android, you just need to import the Gson library, and the rest of them are part of standard Java classes which are supported by Android SDK.
This will download the gson-2.3.1.jar into your system and include them as Maven dependencies in your project's build path if you are using Eclipse.
If you are not using Maven then you have to manually download Gson JAR files from Maven central library or official GitHub page for Gson.
Unlike Jackson, which requires 3 jar files jackson-databind.jar, jackson-annotations.jar, and jackson-core.jar, Gson just requires one JAR file which is gson-2.3.1.jar. You can choose the version you want and I suggest you download the latest stable version but for application, gson-2.3.1.jar is enough.
Now, depending on whether you are running this program in Eclipse or command line you can add this JAR file to your project's classpath for compilation and execution. If you are using Eclipse, then you can follow the steps given here to add any external JAR into Eclipse, Alternatively, you can see the steps given here to add any JAR into CLASSPATH while running your Java program from the command line.
That's all about how to convert a JSON object to JSON String in Java using Google's Gson library. This is the simplest way to convert a Java object to JSON document in an Android or Java application. If you look closely we haven't done anything, we just downloaded the Gson JAR file, added it into our classpath, Created the Gson object, and then call the toJson() method by passing the object we want to convert into JSON.
It cannot be more simple than that. In the next article, we will learn the opposite, like converting JSON String to Java object, also known as JSON deserialization in Java.
Other Java JSON tutorials you may like
Thanks for reading this tutorial so far. If you like this tutorial then please share it with your friends and colleagues. If you have any question or feedback then please drop a comment and I'll try to find an answer for you.
Let's first create that class and call it UserDetails. It contains essential details of a user e.g. name, email, age, phone, city and a boolean field hasCreditCard to indicate that he owns a credit card.
Steps to convert a Java object to JSON String using Gson
Here are the basic steps to convert a Java Object to a JSON document using Google's Gson library. Basically, you give a Java object to this library and it will return a JSON string containing a serialized form of the object's data.
- Download the Gson library and add JAR into the classpath, if you are using Maven just add the dependency in your pom.xml file.
- Create the object you want to convert into JSON
- Create the object of Gson class, a helper class to convert Java object to Gson
- Call the Gson.toJSon(object) to convert the object into JSON String. This method returns a valid JSON containing all fields as defined in the object.
Let's see that class in action, it will look like following
public class UserDetails{ private String name; private String email; private int age; private long phone; private String city; private boolean hasCreditCard; ..... }
This is our simple POJO (Plain old Java object) which we will convert into JSON format. I have committed constructor, getters, and setter for simplicity. Unlike many other frameworks, Gson also doesn't require a default, no-argument constructor.
Now, let's take a close look at this UserDetails class. If you look carefully, it got six attributes, out of those name, email, and the city is String objects, age is an integer that tells how old user is and the phone is a long value to accommodate both 8 digit and 10 digit numbers. It also has a boolean hasCreditCard field to indicate whether the user owns a credit card or not.
The task is now to convert this object to an equivalent JSON String which you can use it on your Android or Java application. If we keep the field names the same, we would expect such a JSON or a normal user which doesn't own a credit card
{ "name": "John", "email": "john.doe@gmail.com", "age": 29, "phone" : 5168161922, "city" : "NewYork", "hasCreditCard": false }
So let's see how we can do the conversion with Gson. First of all, we need to create a Java object for this user
UserDetails user = new UserDetails("John", "john.doe@gmail.com", 29, 5168161922L, "NewYork", false);
In order to serialize this object into equivalent JSON String, we need a Gson object, this is similar to ObjectMapper class of Jackson Databind library, in case you have used it before and trying Gson now. If you have never used any JSON parsing libraries in Java, then just remember, we need a class from the Gson library which will convert our Java object to JSON.
Let's create the object of Gson class for now:
Gson gson = new Gson();
The good thing is that you don't need to pass any parameter to create an instance of Gson class, but it doesn't mean that you cannot configure this object, of course, you can configure the Gson object to suit your need by enabling disabling various configuration parameters, which we'll learn in future articles. For now, let's just focus on serializing a simple Java object to JSON.
Next, we need to call the toJSon() function of Gson and pass the UserDetails object to this method. This will return the JSON String you are looking after.
String json = gson.toJson(user);
The json String will look like the following:
{ "name":"John", "email":"john.doe@gmail.com", "age":29, "phone":5168161922, "city":"NewYork", "hasCreditCard":false }
Even though String would not be as pretty-printed as this but just a single line, you can see that GSon has generated a properly formatted JSON document e.g. String values are properly enclosed within double quotes, while integer values had no wrapping.
There is a comma after every element as well. We didn't have to do anything special, we just call the toJson() method of Gson class and boom, you have your JSON document ready. A single call to Gson was enough to map the entire object. This comes in extremely handy when we're working with a complex data structure.
Java Program to Map an Object to JSON String
Here is a complete Java program to convert a Java object to JSON String using the Google's popular Gson library. You can see that how we have converted an object called UserDetails into their equivalent JSON representation, where attributes are shown as key-value pairs.import com.google.gson.Gson; /** * Java Program to map a Java object to JSON String using Gson library. * * @author WINDOWS 8 * */ public class App { public static void main(String args[]) { UserDetails user = new UserDetails("John", "john.doe@gmail.com", 29, 5168161922L, "NewYork", false); Gson gson = new Gson(); String json = gson.toJson(user); System.out.println(json); } } class UserDetails { private String name; private String email; private int age; private long phone; private String city; private boolean hasCreditCard; public UserDetails(String name, String email, int age, long phone, String city, boolean hasCreditCard) { super(); this.name = name; this.email = email; this.age = age; this.phone = phone; this.city = city; this.hasCreditCard = hasCreditCard; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } 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 isHasCreditCard() { return hasCreditCard; } public void setHasCreditCard(boolean hasCreditCard) { this.hasCreditCard = hasCreditCard; } } Output {"name":"John","email":"john.doe@gmail.com","age":29,"phone":5168161922, "city":"NewYork","hasCreditCard":false}
You can also run this program in Android, you just need to import the Gson library, and the rest of them are part of standard Java classes which are supported by Android SDK.
How to compile and run this program?
In order to compile and run this program, you need to include the Gson JAR files into your classpath. If you are using Maven for dependency management, which you should then you can include the following dependency to download JAR files, any dependency for Gson and automatically include in your project's classpath:<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.3.1</version> </dependency>
This will download the gson-2.3.1.jar into your system and include them as Maven dependencies in your project's build path if you are using Eclipse.
If you are not using Maven then you have to manually download Gson JAR files from Maven central library or official GitHub page for Gson.
Unlike Jackson, which requires 3 jar files jackson-databind.jar, jackson-annotations.jar, and jackson-core.jar, Gson just requires one JAR file which is gson-2.3.1.jar. You can choose the version you want and I suggest you download the latest stable version but for application, gson-2.3.1.jar is enough.
Now, depending on whether you are running this program in Eclipse or command line you can add this JAR file to your project's classpath for compilation and execution. If you are using Eclipse, then you can follow the steps given here to add any external JAR into Eclipse, Alternatively, you can see the steps given here to add any JAR into CLASSPATH while running your Java program from the command line.
That's all about how to convert a JSON object to JSON String in Java using Google's Gson library. This is the simplest way to convert a Java object to JSON document in an Android or Java application. If you look closely we haven't done anything, we just downloaded the Gson JAR file, added it into our classpath, Created the Gson object, and then call the toJson() method by passing the object we want to convert into JSON.
It cannot be more simple than that. In the next article, we will learn the opposite, like converting JSON String to Java object, also known as JSON deserialization in Java.
Other Java JSON tutorials you may like
- How to convert JSON array to String array in Java? (answer)
- How to parse large JSON files using Jackson Streaming API? (example)
- How to use Google Protocol Buffer (protobuf) in Java? (tutorial)
- Top 10 RESTful Web Service Interview Questions (see here)
- What is the purpose of different HTTP methods in REST? (see here)
- 5 Books to Learn REST and RESTful Web Services (books)
- How to consume JSON from RESTful Web Services using RestTemplate of Spring? (tutorial)
- How to convert JSON to HashMap and vice-versa (tutorial)
- How to convert JSON string with date field in Java? (tutorial)
- How to ignore unknown property while paring json in Java? (tutorial)
Thanks for reading this tutorial so far. If you like this tutorial then please share it with your friends and colleagues. If you have any question or feedback then please drop a comment and I'll try to find an answer for you.
Replacing
ReplyDeleteGson gson = new Gson();
with
Gson gson = new GsonBuilder().setPrettyPrinting().create();
formats the output to pretty-printed format.
Thanks a lot))
ReplyDeleteSo clean and perfect tutorial! thank u!
ReplyDelete