Bulk Emailing

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Wednesday, 9 March 2011

JSON- Parsing Apache Lib

Posted on 16:40 by Unknown
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.

Pre-requisites:
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.zip, commons-lang-2.6-bin.zip, ezmorph-1.0.6.jar, commons-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.


Note:
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 ? :-)

Update:
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();
config.setClassMap(classMap);
// Exclude "lat" and "lng" from parsing
config.setExcludes(new String[] {"lat", "lng"});
config.setRootClass(Message.class);
Message m = (Message)JSONObject.toBean(JSONObject.fromObject(json, config), config);
Email ThisBlogThis!Share to XShare to Facebook
Posted in | No comments
Newer Post Older Post Home

0 comments:

Post a Comment

Subscribe to: Post Comments (Atom)

Popular Posts

  • Weekend at Yeouido (Han River Cruise)
    Yeouido is one of the Han River Cruise boarding points. It has a wonderful river side park (Yeouido P...
  • CityWeather
    Update: Release 1.1 has been uploaded. It will now provide weekly forecast of your selected cities. Download   CityWeather is an Android...
  • Few Multi-Threading Implementations
    Sequential Producer & Consumer In my first example, I will demonstrate an implementation to solve ...
  • Accessing Yahoo Finance API
    Since last few days I was wondering the right set of Web Service to read Country wise Stock Exchange index information . I found a bunch of ...
  • Regular Expression in JavaScript
    I was struggling to get familiar with JavaScript's Regular expression handling and thought my learning might help others. Here I'll...
  • Alphanumeric Random Number
    Sometime basic things becomes tricky :-) Was trying to find out ways to generate some alphanumeric random number whose size (i.e. number of ...
  • Binary Search Tree in Java
    This post is a part of my continuous effort to just implement few of the important data structures in ...
  • QuickSort in Java
    This post is a part of my continuous effort to just implement few of the important data structures in Java. Please find my previous post on ...
  • InDroid- Access to Android's Hidden API
    I have started one project " InDroid " to expose and share Hidden and Internal methods and variables of Android platform which are...
  • Image Geo Tagging for Android
    " onMap " is an Image Geo Tagging application, which can read EXIF header of images stored in your Android device and Map them ov...

Blog Archive

  • ►  2013 (6)
    • ►  September (2)
    • ►  May (1)
    • ►  April (1)
    • ►  February (1)
    • ►  January (1)
  • ►  2012 (4)
    • ►  July (2)
    • ►  March (1)
    • ►  January (1)
  • ▼  2011 (11)
    • ►  November (1)
    • ►  October (2)
    • ►  August (1)
    • ►  June (1)
    • ►  April (2)
    • ▼  March (3)
      • Aspect Ratio came to rescue
      • Regular Expression in JavaScript
      • JSON- Parsing Apache Lib
    • ►  January (1)
  • ►  2010 (27)
    • ►  December (2)
    • ►  November (3)
    • ►  September (2)
    • ►  August (4)
    • ►  July (4)
    • ►  June (7)
    • ►  May (5)
Powered by Blogger.

About Me

Unknown
View my complete profile