Monday, February 11, 2013

JSON, stands for JavaScript object notation, is a light weight text or
string representation of object and quickly becoming a popular data exchange
format. Though it's pretty early to say that JSON is going to replace XML
as popular data interchange format, It is certainly providing an alternative.
JSON represent data in two format either an object or an array. JSON object is
an unordered collection of key and value, similar to String
representation of hashtable.
On the other hand JSON Array is an ordered collection of values. Main
difference betweenJSON Object andJSON array is there representation. JSON
object is started with left brace { and ends
with right brace } and key values are separated using colon (:). On the
other hand JSON Array starts with left bracket [ and ends
with right bracket ] and each value is separated
with comma. By looking at structure, You can writeyour JSON parser to parse JSON object or
array to Java object, but you don't need to. There are lot of open source
library in Java which provides tried and tested way of converting JSON String to Java object e.g. Jackson and GSON.
In this Java tutorial we will see example of converting a JSON String to Java object using Jackson library

How to convert JSON String to Java object
using Jackson

It's very easy to create Java object from JSON String using Jackson
library. It's literally require two lines of code to do this, as shown in
following Java example. If you look at code, most of code is for creating Java
class e.g. User in this case, while code required to convert JSON String to Java object is
just two lines in fromJson(String json) method. This method takes
an Jon String which represent a User object in JSON format and
convert it into Java User object. In this Java example I have create
User as nested
static class for convenience, You may create a separate top
level class if needed.

importjava.io.IOException;

importorg.apache.log4j.Logger;

importorg.codehaus.jackson.JsonParseException;

importorg.codehaus.jackson.map.JsonMappingException;

importorg.codehaus.jackson.map.ObjectMapper;

/*

* Java program to convert
JSON String into Java object using Jackson library.

* Jackson is very easy to
use and require just two lines of code to create a Java object

As I said, You can either use Jackson or Gson to convert JSON
String to Java object and in this Java tutorial we have used Jackson
library for JSON to Java object conversion. If you are using Maven for
dependency management than you can add following dependency in POM.xml :

That's all on How to convert JSON String to Java object using Jackson
library. Though, this is a trivial example and actual object could be more
complex, it demonstrate the process of creating Java object from JSON String.
You can also use other JSON library like GSON instead of Jackson to convert
JSON String to Java object. Full list of JSON libraries are available on http://www.json.org/.