Sunday, October 31, 2010

JSON, Java, JSONSimple, Exposed Web services and all that jazz.

First off JSON is fun stuff and its everywhere. JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. Almost all web services when invoked return JSON data.

Here is a sample show JSON looks like:


There's even a 3 minute tutorial on how to understand it.

Once you understood what JSON is, then its time to do something with it. In my case, is to process (or parse) it using Java and taking the lazy way out, use a toolkit that somebody else wrote to parse it - JSONSimple.

The thing with JSONSimple is that it maps JSON stuff into Java Collections types like List and Map.
Here is another sample on how to use it:
 String s="[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";  
 Object obj=JSONValue.parse(s);  
 JSONArray array=(JSONArray)obj;  
 System.out.println("======the 2nd element of array======");  
 System.out.println(array.get(1));  
 System.out.println();  
           
 JSONObject obj2=(JSONObject)array.get(1);  
 System.out.println("======field \"1\"==========");  
 System.out.println(obj2.get("1"));       


See their website for more encoding and decoding examples using JSONSimple.

1 comment:

  1. Good article. Make it more describable,following link seems a good tutorial on JSON.
    http://www.w3resource.com/JSON/introduction.php

    ReplyDelete