Searching...
Wednesday, 19 September 2012

Jackson API : Java Object to Json and Json to Java

05:00

JSON
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.
Here is one example how Jackson is convert a java object in to JSON and JSON to Java Object.

Create a Maven Project and add below dependencies

<repositories>
        <repository>
            <id>codehaus</id>
            <url>http://repository.codehaus.org/org/codehaus</url>
        </repository>
    </repositories>
    <dependencies>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.8.5</version>
        </dependency>
    </dependencies>

Note: After maven clean make sure that jackson-mapper and jackson-core jars are added in the dependencies.

Test class

package com.vinod.test;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;

public class ObjectToJson {
    public static void main(String[] args) {
        Customer customer = new Customer("vinod", "bangalore");
        ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
        try {
            // Object to JSON String
            String customerJson = ow.writeValueAsString(customer);
            System.out.println(customerJson);

            // Json String to object
            ObjectMapper mapper = new ObjectMapper();

            Customer cus = mapper.readValue(customerJson, Customer.class);
            System.out.println(cus);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

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 + "]";
    }

}

Output

{

  "address" : "bangalore",

  "name" : "vinod"

}

Customer [name=vinod, address=bangalore]

 

 


0 comments: