Thursday, March 10, 2011

JSON- Parsing Apache Lib

I'm back again, last few months I was busy with my own Web 2.0 project and trying to build a platform which will use advance JavaScript and once that is done will write a JSON based Web API which can be accessed from Mobiles. So, thought lets share few exploration on Javascript and JSON. Here I'll explain how we can efficiently parse JSON to Java Object and vice verse. So if you are looking for similar stuff, keep reading following sections...
JSON (JavaScript Object Notation) is an wonderful and light weight piece of Object notation for data exchange. If you compare this with XML, you can easily make out that this representation is pretty compact compared to XML which need to use extra piece of information (XML Node name, start and end tags) to distinguish each node. Moreover JSON is closer to Object representation of your programming language Java or it is very easily supported in JavaScript (eval()). So if you are using
AJAX, this is the best fit.

So, next time you are planning to develope a data exchange system probably you can choose JSON instead of XML.

I will demonstrate 2 important portions of data exchange modules- 
Convert data from your native Objects (Java Objects) to JSON and get data back from JSON to your native Objects (Java Objects).
This conversion should be generic enough and easy to do, so that you can seemlessly add this exchange module without worrying too much about your present Object model.

I am using Apache JSON-Lib (JDK1.5). The library is wonderfull, but the document doesn't indicate all dependent libraraies. So, make sure you download below Apache JARs as well-

commons-beanutils-1.8.3-bin.zipcommons-lang-2.6-bin.zipezmorph-1.0.6.jarcommons-collections-3.1.jar and commons-io-2.0.1.jar

The reason I am writting this is, there is no straight forward answer on Apache site which explains how to convert JSON to Java and vice verse for Complex Objects.

Lets start with the Object structure that we'll use to do JSON to Java and Java to JSON.

Please make sure your create Java Bean compatible Get and Set methods.

Java code to convert Bean object to JSON String-
Message m = new Message()
// Steps to fill in data into Message object
// Now, convert Java object to JSON
JSON json = JSONSerializer.toJSON(m);
String jsonString = json.toString();

Thats it! The Libraray it self is awesome, but need some more document, otherwise it takes time to figure out its features.

Now, lets do things in reverse i.e. convert JSON string to Java object. For this I'll use the String that I have just converted from my message Class-
    "ads" : {
        "lat" : 23.789,
        "lng" : 56.89,
        "location" : "out of the world"
    "arrayAds" : [{
            "lat" : 23.567,
            "lng" : 45.678,
            "location" : "A1"
        }, {
            "lat" : 23.567,
            "lng" : 45.678,
            "location" : "A2"
    "id" : 1,
    "msg" : "Hi, its me",
    "recipents" : ["u123 thy", "u234"],
    "sender" : "Alan"

Java code to convert JSON string to Java Bean Object-
Declare the type of Custom Object ArrayList you are going to use. In my example class, Message has a member variable arrayAds, an ArrayList of Address class (Custom Object)

Map classMap = new HashMap();
classMap.put("arrayAds", Address.class);

Declare your base class i.e. Message.class. toBean() method does the parsing using Java refactor technology.

Message m = (Message)JSONObject.toBean(
JSONObject.fromObject(json), Message.class, classMap);

Thats it! Now you can access the Message object "m". How good is that ? :-)

If you want to skip any field, say you don't want to parse lat and lng values from JSON stream. To do this we have to use JsonConfig class.

// Define your Configuration
JsonConfig config = new JsonConfig();
// Exclude "lat" and "lng" from parsing
config.setExcludes(new String[] {"lat", "lng"});
Message m = (Message)JSONObject.toBean(JSONObject.fromObject(json, config), config);

1 comment:

  1. This is quite similar to jackson JSON parser, have a look at it :

    It's known to have better performance than other json parser.