Searching...
Wednesday, 19 September 2012

Gson API : Java object -> Json and Json -> Java object Example

07:53

JSON
JavaScript Object Notation is a popular alternative for xml and it is very simple and easy to read and write data exchange format. There are lot of third party libraries are available to processing JSON data like JSON.simple,Jackson,Gson etc

Gson
Gson is a Open sources API from Google to convert Java object to JSON representation and JSON to Java Object. The source code is available in Google site (http://code.google.com/p/google-gson)

Example:

Create a Maven Project and add below dependencies

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

Note: After maven clean make sure that gson jars are added in the dependencies.

Create a POJO class

package com.vinod.test;

public class Customer {
    public Customer(String name, String address) {
        super();
        this.name = name;
        this.address = address;
    }
    public Customer() {}
    private String name;
    private String address;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    @Override
    public String toString() {
        return "Customer [name=" + name + ", address=" + address + "]";
    }
}
 

Create a Test class

package com.vinod.test;

import com.google.gson.Gson;

public class GsonExample {

    public static void main(String args[]) {
        Gson gson = new Gson();

        // convert java object to JSON format,
        Customer customer = new Customer("vinod", "Bangalore");
        String customerJson = gson.toJson(customer);
        System.out.println(customer);
        // convert json to java object
        Customer cust = gson.fromJson(customerJson, Customer.class);
        System.out.println(cust);

    }
}
 

Output

Customer [name=vinod, address=Bangalore]

Customer [name=vinod, address=Bangalore]

 

Done!!!


0 comments: