JSON To And From Java Object Using Gson and Jackson Apis

For any REST service converting JSON to and from Java object is a very common requirement.  If you use Jersey API the conversion of JSON to Java object or Java object to JSON happen implicitly.  There are many situations where you may need to do the conversion manually.  Here two examples using two libraries to perform the conversion.

Convert Json to and from Java Using Gson (Google) Library

Library required – gson-2.2.jar

It can be downloaded from http://www.java2s.com/Code/Jar/g/Downloadgson22jar.htm

package com.javamadeeasy;
 
import com.google.gson.Gson;
 
public class ConvertJsonWithGson {
 
	public static void main(String args[]) {
		String json = "{\"name\":\"Head First Java\",\"serialNumber\":1}";
		Gson gson = new Gson();
 
		//Convert Json string to Java
		Book book = gson.fromJson(json, Book.class);
		System.out.println("JSON To Java mapped ");
		System.out.println(book.getName()+" - "+book.getSerialNumber());
 
		//Convert Java to Json string
		String convertedJson = gson.toJson(book);
		System.out.println("Json from Book : "+convertedJson);
	}
}

Here is the Output

JSON To Java mapped 
Head First Java - 1
Json from Book : {"name":"Head First Java","serialNumber":1}

Convert Json to and from Java Using Jackson Library

Jar file required – jackson-all-1.9.0.jar

It can be downloaded from http://www.java2s.com/Code/Jar/j/Downloadjacksonall190jar.htm

package com.javamadeeasy;
 
import java.io.IOException;
 
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
 
public class ConvertJsonWithJackson {
	public static void main(String args[]) throws JsonParseException, JsonMappingException, IOException {
		String json = "{\"name\":\"Head First Java\",\"serialNumber\":1}";
		ObjectMapper objectMapper = new ObjectMapper();
 
		//Convert Json string to Java
		Book book = objectMapper.readValue(json, Book.class);
		System.out.println("JSON To Java mapped ");
		System.out.println(book.getName()+" - "+book.getSerialNumber());
 
		//Convert Java to Json string
		String convertedJson = objectMapper.writeValueAsString(json);
		System.out.println("Json from Book : "+convertedJson);
 
	}
}

Here is the Output

JSON To Java mapped 
Head First Java - 1
Json from Book : "{\"name\":\"Head First Java\",\"serialNumber\":1}"