Saturday, November 9, 2019

How To Convert Coffee Object To Json String - Gson Java/Json Serialization Example

If y'all 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 elementary way to convert your Java object into json format therefore y'all get got come upwardly to the correct place. In this article, I'll learn y'all how to convert a Java object to JSON document using Google's Java library called Gson. This library allows y'all to convert both Java object to JSON String together with a JSON document to Java object. So, let's showtime exercise to a greater extent than or less 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 amongst lots of attributes together with nested amongst composed object but for now, we'll start amongst a course of written report which simply incorporate few value attributes e.g. String, int together with boolean.

Let's showtime exercise that a course of written report together with telephone yell upwardly it UserDetails. It contains essential details of a user e.g. name, email, age, phone, urban center together with a boolean champaign hasCreditCard to betoken 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, y'all give Java object to this library together with it volition provide a JSON string containing serialized shape of object's data. 
  1. Download Gson library together with add together JAR into the classpath, if y'all are using Maven simply add together the dependency inwards your pom.xml file.
  2. Create the object y'all desire to convert into JSON
  3. Create the object of Gson class, a helper course of written 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 equally defined inwards the object. 


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

Now, let's get got a unopen human face at this UserDetails class. If y'all human face carefully, it got half-dozen attributes, out of those name, email, together with a urban center is String objects, historic menstruation is an integer which tells how one-time user is together with the telephone is a long value to conform both 8 digit together with 10 digit numbers. It equally good has a boolean hasCreditCard champaign to betoken whether the user owns a credit bill of fare or not.


The chore is directly to convert this object to an equivalent JSON String which y'all tin usage it on your Android or Java application. If nosotros buy the farm along the champaign names the same, nosotros would hold off 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 exercise the conversion amongst Gson. First of all, nosotros involve to exercise a Java object for this user

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

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


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

Gson gson = new Gson();

Good matter is that y'all don't involve to overstep whatever parameter to exercise an instance of Gson class, but it doesn't hateful that y'all cannot configure this object, of course, y'all tin configure Gson object to suit your involve yesteryear enabling disabling diverse configuration parameters, which we'll larn inwards futurity articles. For now, let's simply focus on serializing a elementary Java object to JSON.

Next, nosotros involve to telephone yell upwardly the toJSon() role of Gson together with overstep the UserDetails object to this method. This volition provide the JSON String y'all are looking after.

String json = gson.toJson(user);

The json String volition human face similar following:

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

Even though String would non move equally pretty printed equally this but simply a unmarried line, y'all 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 afterward every chemical constituent equally well. We didn't get got to exercise anything special, nosotros simply telephone yell upwardly the toJson() method of Gson course of written report together with boom, y'all get got your JSON document ready. H5N1 unmarried telephone yell upwardly to Gson was plenty to map the entire object. This comes inwards extremely handy when we're working amongst a complex information structure.




Java Program to Map an Object to JSON String

Here is consummate Java plan to convert a Java object to JSON String using Google Gson library. You tin encounter that how nosotros get got converted an object called UserDetails into their equivalent JSON representation, where attributes are shown equally 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 equally good run this plan inwards Android, y'all simply involve to import Gson library together with residue of them are constituent of criterion Java classes which are supported yesteryear Android SDK.

 If y'all 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 lodge to compile together with run this program, y'all involve to include the Gson JAR files into your classpath. If y'all are using Maven for dependency management, which y'all should therefore y'all 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 organisation together with include them equally Maven dependencies inwards your project's build path if y'all are using Eclipse.

If y'all are non using Maven therefore y'all get got to manually download Gson JAR files from Maven key library or official GitHub page for Gson.


Unlike Jackson, which requires iii jolt files jackson-databind.jar, jackson-annotations.jar, together with jackson-core.jar, Gson simply require 1 JAR file which is gson-2.3.1.jar. You tin select the version y'all desire together with I advise y'all download the latest stable version but for application, gson-2.3.1.jar is enough.

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


That's all virtually 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 y'all human face closely nosotros haven't done anything, nosotros simply downloaded Gson JAR file, added into our classpath, Created Gson object together with therefore telephone yell upwardly the toJson() method yesteryear passing the object nosotros desire to convert into JSON.

It cannot move to a greater extent than elementary than that. In the adjacent article, nosotros volition larn opposite, i.e. converting JSON String to Java object, equally good known equally JSON deserialization inwards Java.

Further Learning
Master Java Web Services together with REST API amongst Spring Boot
REST API Design, Development & Management
answer)
  • How to parse large JSON file using Jackson Streaming API? (example)
  • How to usage Google Protocol Buffer (protobuf) inwards Java? (tutorial)
  • Top 10 RESTful Web Service Interview Questions (see here)
  • What is the piece of job of unlike 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 y'all similar this tutorial therefore delight portion amongst your friends together with colleagues. If y'all get got whatever enquiry or feedback therefore delight drib a comment together with I'll endeavor to discovery an respond for you.

    No comments:

    Post a Comment