Parsing JSON in Java.

Parsing of JSON can be done using some of the opensource libraries such as Google-GSON , Serotonin , FastJSON and many more. I use a simple library named Argo, small and easy to use. It can be downloaded fromĀ http://argo.sourceforge.net/. It’s documentation is also very simple. An Example JSON file looks something like this :

{
"status" : "OK",
"data" : { 
          "train_name" : "ERNAKULAM EXP",
          "train_number" : "12677",
          "from" :  {"name" : "Bangalore City" , "code":"SBC"},
          "to" :  {"name" : "Coimbatore Jn." , "code":"CBE"},
          "alight" : {"name" : "Coimbatore Jn." , "code":"CBE"},
          "board" : {"name" : "Bangalore City" , "code":"SBC"},
          "class" : "2S",
          "travel_date" : "2-6-2011"
          "passenger" : [ { "seat_number" : "D8  , 31,GN", "status" : "CNF" },
                          { "seat_number" : "D8  , 32,GN", "status" : "CNF" } ],
          "chart_prepared" : false
         }
}

So the code snippet to get the train_name (Train Name) looks something like this.

String secondSingle = new JdomParser().parse(out).getStringValue("data","train_name");

Similarly finding other fields could be done similarly by just separating the fields by commas and then getting the values.

In case you have an array as the value instead you can also use the index number like :

<pre>
String secondSingle = new JdomParser().parse(out).getStringValue("data","train_name","some_field",1);</pre>

In this case you can get the value at first index in some_field.

In case of doubts you can refer the documentation available here :

http://argo.sourceforge.net/javadoc/