Tuesday, November 8, 2016

Creating a JSON parser using Java

Aim:
In this exercise we will create a Json parser with Java

Language Used:
Java

Code:
https://github.com/csanuragjain/extra/tree/master/JSON%20Parser

Dependency:
Please add below maven dependency which we got from http://mvnrepository.com/artifact/org.json/json/20160810 in your pom.xml:

 <dependency>  
   <groupId>org.json</groupId>  
   <artifactId>json</artifactId>  
   <version>20160810</version>  
 </dependency>  

Our Sample JSON:
 {  
   "student": {  
      "rNo": "1",  
      "Name": "Anurag",  
            "Website": "https://cooltrickshome.blogspot.com"  
   },  
   "posts": [  
      {  
        "post": "Create Keylogger with Java",  
        "url": "http://cooltrickshome.blogspot.com/2016/11/creating-your-personal-keylogger-from.html"  
      }  
   ]  
 }  


Program:


 package com.cooltrickshome;  
 import org.json.*;  
 public class JSONParser {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           String json = "{\"student\":{\"rNo\":\"1\",\"Name\":\"Anurag\",\"Website\":\"https://cooltrickshome.blogspot.com\"},\"posts\":[{\"post\":\"Create Keylogger with Java\",\"url\":\"http://cooltrickshome.blogspot.com/2016/11/creating-your-personal-keylogger-from.html\"}]}";  
           JSONObject obj = new JSONObject(json);  
           String name = obj.getJSONObject("student").getString("Name");  
           String website = obj.getJSONObject("student").getString("Website");  
           System.out.println("Name: "+name);  
           System.out.println("Website: "+website);  
           JSONArray arr = obj.getJSONArray("posts");  
           System.out.println("Printing posts by this author");  
           for (int i = 0; i < arr.length(); i++)  
           {  
             String post = arr.getJSONObject(i).getString("post");  
             String url = arr.getJSONObject(i).getString("url");  
             System.out.println(post+" at "+url);  
           }  
      }  
 }  

How it works:

1) First we define the input json inside a variable called json. Make sure you escape all " with \" otherwise java would show compilation error

2) We create JSONObject object and pass our json variable

3) Both name and website lye within student node in json. So we simply use getJSONObject("student") to reach student node and then we use getString("Name") to extract the name which is string

4) Similarly we get the website using getString("Website")

5) Now you will notice that the posts node in json is an array (notice []) which had one post.

6) So first we use getJSONArray("posts") to point to our posts array and then use a for loop to navigate through each of its value

7) Now each posts node contain 2 subnode which is post & url. So we use getJSONObject(i) which points to our first post when i is 0 and then we use getString("post") to get the post and getString("url") to get the url.

8) These all could have been stored if you need them in your program by using Map. For example if we wanted to keep Name & Website for future use, we can store it as:

 Map author = new LinkedHashMap(); 
 author.put("Name", name); 
 author.put("Website", website); 

Hope it helps :)

2 comments:

  1. Alternatively, you could add Groovy and use its JsonSlurper. Maybe I'm just too lazy.
    John

    ReplyDelete
    Replies
    1. Thanks a lot for the suggestion. I will definitely take a look, learn and try to post a blog on using JsonSlurper :)

      Delete