Parsing Logic

parse json java

Introduction parse json java:

JSON (Java Script Object Notation) is a light weight data interchange format is now being used as a profound and efficient way of gathering, collecting or share data among applications and interfaces. Parse json java provides data to its corresponding calling function in key, value pairs. ‘Key’ as in the variable and ‘value’ as in the corresponding value for the variable. The data that is parsed from a JSON API is in the form of objects which needs to be converted into their respective data format as acceptable by the system.

I won’t go into much details into describing API’s in this blog post. May be I will in my upcoming blog posts. REST (Representational State Transfer) is an architectural style and is an approach to communications between different modules that is often used in the development of web services. So in this blog I would describe how can you use parse json java to leverage JSON data from a REST API.

Before starting here is the REST API I am using to parse data into my system JSON-API.

Now what is the use of parsing JSON data from a web service when I can have it in my system already ? The answer to that would be now a days maximum of the client data is available over the web as it is not prone to data loss. More over clients built around JSON API are able to take advantage of its features around efficiently caching responses, sometimes eliminating network requests entirely. So let’s proceed ahead and I would try to explain the process of jason parsing the data step wise using java json library.

Step by step for Json Parsing with Example:

Step-1) Pass the desired URL as an object. So that would be like

URL url = new URL(“The required URL”);

Step-2) Type cast the URL object into a HttpURLConnection object. The benefit of doing it is that we would be able to harness the properties of the HttpURLConnection class to json validator features. For java json parser example set the request type or check the status of the response code.

HttpURLConnection conn = (HttpURLConnection)url.openConnection();

Step-3) Set the request type as in whether the request to the API is a GET request or a POST request.

conn.setRequestMethod(“GET”);

Step-4) Open a connection stream to the corresponding API.

conn.connect();

Step-5) Get the corresponding response code.

int responsecode = conn.getResponseCode();

Step-6) Now I need to perform a check that if response code is not 200 then throw a runtime exception otherwise carry on the rest of the procedure. So the structure would be

if(responsecode != 200)
  throw new RuntimeException("HttpResponseCode: " +responsecode);
else
{
  Next part of the functionality
}

Step-7) I have used the method scanner to read each line from the API and fetch the data in string format. Now this part is inside else { } that I mentioned above.

Scanner sc = new Scanner(url.openStream());
while(sc.hasNext())
{
 inline+=sc.nextLine();xample
}
System.out.println(“\nJSON data in string format”);
System.out.println(inline);
sc.close();

So the parsed data would something like this

{ "results" : [ { "address_components" : [ { "long_name" : "Chicago", "short_name" : "Chicago", "types" : [ "locality", "political" ] }, { "long_name" : "Cook County", "short_name" : "Cook County", "types" : [ "administrative_area_level_2", "political" ] }, { "long_name" : "Illinois", "short_name" : "IL", "types" : [ "administrative_area_level_1", "political" ] }, { "long_name" : "United States", "short_name" : "US", "types" : [ "country", "political" ] } ], "formatted_address" : "Chicago, IL, USA", "geometry" : { "bounds" : { "northeast" : { "lat" : 42.023131, "lng" : -87.52404399999999 }, "southwest" : { "lat" : 41.6443349, "lng" : -87.9402669 } }, "location" : { "lat" : 41.8781136, "lng" : -87.6297982 }, "location_type" : "APPROXIMATE", "viewport" : { "northeast" : { "lat" : 42.023131, "lng" : -87.52404399999999 }, "southwest" : { "lat" : 41.6443349, "lng" : -87.9402669 } } }, "place_id" : "ChIJ7cv00DwsDogRAMDACa2m4K8", "types" : [ "locality", "political" ] } ], "status" : "OK"}

Now you have all the data with you from the API. But somehow it looks a bit unstructured and definitely you would need the data categorically and not all the data as a whole. So for this you need to parse this data into JSON object. In some cases you need to store the data in JSON array as well.

Parse json java by default does not have any inbuilt class or projovide any inbuilt class and method to parse and store these data as objects. So for that you need the class JSONObject (to store the corresponding string data as JSON object), Jsonarray java (to hold JSON object in an array) and JSONParser (to convert string object into JSON object). For that you will need a package called Json simple. Json download the required jar files and configure its class path in the system.

Step-8) Declare an instance of the JSONParser

JSONParser parse = new JSONParser();

Step-9) Convert the string objects into JSON object.

JSONObject jobj = (JSONObject)parse.parse(inline);

So if you view the JSON structure which would be something like this

{
   "results" : [
      {
	   "place_id" : "ChIJ7cv00DwsDogRAMDACa2m4K8",
         "types" : [ "locality", "political" ]
      } ]
}

I wold now like to get the corresponding values under the results array. So here how you do it

Step-10) First convert the JSON object into JSONArray object like this

JSONArray jsonarr_1 = (JSONArray) jobj.get(“results”);

Step-11) Once the JSON objects are stored in the array, read the corresponding JSONArray objects, convert it to JSON objects again. So you get the elements within the results array. So here is how you do it.

//Get data for Results array

 for(int i=0;i<jsonarr_1.size();i++)
 {
   //Store the JSON objects in an array
   //Get the index of the JSON object and print the values as per the index
  JSONObject jsonobj_1 = (JSONObject)jsonarr_1.get(i);
  System.out.println("Elements under results array");
  System.out.println("\nPlace id: " +jsonobj_1.get("place_id"));
  System.out.println("Types: " +jsonobj_1.get("types"));
}

So, let us dig a bit deeper. Now let us suppose I want the components of “address_components”. Here is the JSON structure

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Chicago",
               "short_name" : "Chicago",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Cook County",
               "short_name" : "Cook County",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Illinois",
               "short_name" : "IL",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "United States",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            }
         ]
So how would I get the components under the address_components array? Follow the same step as above
//Parse the JSON data present in the string format
 JSONParser parse = new JSONParser();
//Type caste the parsed json data in json object
 JSONObject jobj = (JSONObject)parse.parse(inline);
//Store the JSON object in JSON array as objects (For level 1 array element i.e Results)
 JSONArray jsonarr_1 = (JSONArray) jobj.get("results
//Get data for Results array
 for(int i=0;i<jsonarr_1.size();i++)
 {
    //Store the JSON objects in an array
    //Get the index of the JSON object and print the values 
    //as per the index
    JSONObject jsonobj_1 = (JSONObject)jsonarr_1.get(i);
    //Store the JSON object in JSON array as objects (For level 2 array element i.e Address Components)
    JSONArray jsonarr_2 = (JSONArray) jsonobj_1.get("address_components");
    System.out.println("Elementsr results array");
    System.out.println("\nPlace" +jsonobj_1.get("place_id"));
    System.out.println("Typesjsonobj_1.get("types"));
    //Get data for the Address Components array
    System.out.println("Elementsr address_components array");
    System.out.println("The names, short names and types are:");
    for(int j=0;j<jsonarr_2.size();j++)
    {
      //Same just store the JSON objects in an array
     //Get the index of the JSON objects and print the values as per the index
     JSONObject jsonobj_2 = (JSONObject) jsonarr_2.get(j);
     //Store the data as String objects
     String str_data1 = (String) jsonobj_2.get("long_name");
     System.out.println(str_data1);
     String str_data2 = (String) jsonobj_2.get("short_name");
     System.out.println(str_data2);
     System.out.println(jsonobj_2.get("types
     System.out.println("\n
    }
}

Here is the git hub link to help you out Parsing Data from JSON REST API

 
Soumyajit Basu

Leave a Reply

Your email address will not be published. Required fields are marked *