How to convert Java object to JSON String - Gson Java/JSON Serialization Example

If yous are a Java or Android developer together with learning JSON to back upwardly JSON format for your projection together with looking for a quick together with uncomplicated way to convert your Java object into json format therefore yous cause got come upwardly to the correct place. In this article, I'll learn yous how to convert a Java object to JSON document using Google's Java library called Gson. This library allows yous to convert both Java object to JSON String together with a JSON document to Java object. So, let's root practise unopen to serialization. Serialization inwards the context of Gson agency mapping a Java object to its JSON representation. In the existent world, the information tin move actually complex alongside lots of attributes together with nested alongside composed object but for now, we'll start alongside a course of report which simply incorporate few value attributes e.g. String, int together with boolean.

Let's root practise that a course of report together with telephone phone it UserDetails. It contains essential details of a user e.g. name, email, age, phone, metropolis together with a boolean champaign hasCreditCard to signal that he owns a credit card.


Steps to convert a Java object to JSON String
Here are the basic steps to convert a Java Object to a JSON document using Google's Gson library. Basically, yous give Java object to this library together with it volition furnish a JSON string containing serialized cast of object's data. 
  1. Download Gson library together with add together JAR into the classpath, if yous are using Maven simply add together the dependency inwards your pom.xml file.
  2. Create the object yous desire to convert into JSON
  3. Create the object of Gson class, a helper course of report to convert Java object to Gson
  4. Call the Gson.toJSon(object) to convert the object into JSON String. This method returns a valid JSON containing all fields every bit defined inwards the object. 


Let's encounter that course of report inwards action, it volition aspect similar 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 uncomplicated POJO (Plain one-time Java object) which nosotros volition convert into JSON format. I cause got committed constructor, getters, together with setter for simplicity. Unlike many other frameworks, Gson every bit good doesn't require a default, no-argument constructor.

Now, let's cause got a unopen aspect at this UserDetails class. If yous aspect carefully, it got half-dozen attributes, out of those name, email, together with a metropolis is String objects, historic menstruum is an integer which tells how one-time user is together with the telephone is a long value to suit both 8 digit together with 10 digit numbers. It every bit good has a boolean hasCreditCard champaign to signal whether the user owns a credit carte or not.


The chore is straightaway to convert this object to an equivalent JSON String which yous tin exercise it on your Android or Java application. If nosotros come about the champaign names the same, nosotros would aspect such a JSON or a normal user which doesn't ain a credit card

{ "name": "John", "email": "john.doe@gmail.com", "age": 29, "phone" : 5168161922, "city" : "NewYork", "hasCreditCard": faux }

So let's encounter how nosotros tin practise the conversion alongside Gson. First of all, nosotros bespeak to practise a Java object for this user

UserDetails user = new UserDetails("John",                                 "john.doe@gmail.com",                                  29,                                  5168161922L,                                  "NewYork",                                  false);

In fellowship to serialize this object into equivalent JSON String, nosotros bespeak a Gson object, this is similar to ObjectMapper class of Jackson Databind library, inwards instance yous cause got used it earlier together with trying Gson now. If yous cause got never used whatever JSON parsing libraries inwards Java, therefore simply remember, nosotros bespeak a course of report from the Gson library which volition convert our Java object to JSON.


Let's practise the object of Gson course of report for now:

Gson gson = new Gson();

Good matter is that yous don't bespeak to transcend whatever parameter to practise an instance of Gson class, but it doesn't hateful that yous cannot configure this object, of course, yous tin configure Gson object to suit your bespeak past times enabling disabling diverse configuration parameters, which we'll larn inwards hereafter articles. For now, let's simply focus on serializing a uncomplicated Java object to JSON.

Next, nosotros bespeak to telephone phone the toJSon() role of Gson together with transcend the UserDetails object to this method. This volition furnish the JSON String yous are looking after.

String json = gson.toJson(user);

The json String volition aspect similar following:

{   "name":"John",   "email":"john.doe@gmail.com",   "age":29,   "phone":5168161922,   "city":"NewYork",   "hasCreditCard":false }

Even though String would non move every bit pretty printed every bit this but simply a unmarried line, yous tin encounter that GSon has generated a properly formatted JSON document e.g. String values are properly enclosed inside double quotes, piece integer values had no wrapping.

There is a comma afterwards every chemical ingredient every bit well. We didn't cause got to practise anything special, nosotros simply telephone phone the toJson() method of Gson course of report together with boom, yous cause got your JSON document ready. H5N1 unmarried telephone phone to Gson was plenty to map the entire object. This comes inwards extremely handy when we're working alongside a complex information structure.




Java Program to Map an Object to JSON String

Here is consummate Java programme to convert a Java object to JSON String using Google Gson library. You tin encounter that how nosotros cause got converted an object called UserDetails into their equivalent JSON representation, where attributes are shown every bit 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 tin every bit good run this programme inwards Android, yous simply bespeak to import Gson library together with residuum of them are portion of measure Java classes which are supported past times Android SDK.

 If yous are a Java or Android developer together with learning JSON to back upwardly JSON format for your  How to convert Java object to JSON String - Gson Java/JSON Serialization Example


How to compile together with run this program?

In fellowship to compile together with run this program, yous bespeak to include the Gson JAR files into your classpath. If yous are using Maven for dependency management, which yous should therefore yous tin include the next dependency to download JAR files, whatever dependency for Gson together with automatically include inwards your project's classpath:

<dependency>   <groupId>com.google.code.gson</groupId>   <artifactId>gson</artifactId>   <version>2.3.1</version> </dependency>

This volition download the gson-2.3.1.jar into your organization together with include them every bit Maven dependencies inwards your project's build path if yous are using Eclipse.

If yous are non using Maven therefore yous cause got to manually download Gson JAR files from Maven fundamental library or official GitHub page for Gson.


Unlike Jackson, which requires three scandalize files jackson-databind.jar, jackson-annotations.jar, together with jackson-core.jar, Gson simply require ane JAR file which is gson-2.3.1.jar. You tin direct the version yous desire together with I propose yous download the latest stable version but for application, gson-2.3.1.jar is enough.

Now, depending on whether yous are running this programme inwards Eclipse or ascendancy trouble yous tin add together this JAR file to your project's classpath for compilation together with execution. If yous are using Eclipse, therefore yous tin follow steps given here to add together whatever external JAR into Eclipse, Alternatively, yous tin encounter steps given here to add together whatever JAR into CLASSPATH piece running your Java programme from ascendancy line.


That's all close how to convert a JSON object to JSON String inwards Java using Google's Gson library. This is the simplest way to convert a Java object to JSON document inwards Android or Java application. If yous aspect closely nosotros haven't done anything, nosotros simply downloaded Gson JAR file, added into our classpath, Created Gson object together with therefore telephone phone the toJson() method past times passing the object nosotros desire to convert into JSON.

It cannot move to a greater extent than uncomplicated than that. In the side past times side article, nosotros volition larn opposite, i.e. converting JSON String to Java object, every bit good known every bit JSON deserialization inwards Java.


Other Java JSON tutorials yous may like
  • How to convert JSON array to String array inwards Java? (answer)
  • How to parse large JSON file using Jackson Streaming API? (example)
  • How to exercise Google Protocol Buffer (protobuf) inwards Java? (tutorial)
  • Top 10 RESTful Web Service Interview Questions (see here)
  • What is the role of dissimilar HTTP methods inwards REST? (see here)
  • 5 Books to Learn REST together with RESTful Web Services (books)
  • How to eat JSON from RESTful Web Services using RestTemplate of Spring? (tutorial)
  • How to convert JSON to HashMap together with vice-versa (tutorial)


Thanks for reading this tutorial therefore far. If yous similar this tutorial therefore delight portion alongside your friends together with colleagues. If yous cause got whatever query or feedback therefore delight drib a comment together with I'll endeavor to honor an respond for you.

Subscribe to receive free email updates:

0 Response to "How to convert Java object to JSON String - Gson Java/JSON Serialization Example"

Posting Komentar