I won ’ thymine go into much detail describing APIs in this web log military post. REST ( Representational State Transfer ) is an architectural style and is an approach to communications between different modules frequently used in the development of vane services. In this web log, I will describe how you can use JAVA to leverage JSON data from a REST API .
Before starting hera is the REST API I am using to parse data into my organization JSON-API .
immediately what is the habit of parsing JSON data from a web service when I can have it in my system already ? The answer to that would be immediately a days maximal of the node data is available over the network 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 wholly. So lashkar-e-taiba ’ s proceed ahead and I would try to explain the march of parsing the data step judicious.
Step 1) Pass the hope URL as an object :
URL url = new URL(“The required URL”);
Step 2) Type cast the URL object into a HttpURLConnection object. The benefit of doing this is that we will be able to harness the properties of the HttpURLConnection class to validate features. For exercise, set the request type or check the condition of the answer 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 comparable reaction code .
int responsecode = conn.getResponseCode();
Step 6) immediately we need to perform a check so that if the reply code is not 200, we throw a runtime exception, or otherwise carry on the rest of the procedure. The structure would be like this :
if(responsecode != 200)
throw new RuntimeException(“HttpResponseCode: “ +responsecode);
else
{
Next part of the functionality
}
Step 7) I have used the method acting scanner to read each line from the API and fetch the data in bowed stringed instrument format. now, this separate is at heart else { } like I mentioned above.
Scanner sc = new Scanner(url.openStream());
while(sc.hasNext())
{
inline+=sc.nextLine();
}
System.out.println(“\nJSON data in string format”);
System.out.println(inline);
sc.close();
The parsed data will 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. Somehow, it looks a spot amorphous, and you will decidedly need the data flatly and not all the data as a whole. For this, you need to parse this datum into a JSON aim. In some cases, you need to store the data in JSON array arsenic well .
JAVA by default does not have any built-in class or provide any built-in class and method acting to parse and store these data as objects, therefore for that, you need the class JSONObject ( to store the correspond chain data as JSON objects ), JSONArray ( to hold JSON objects in an array ) and JSONParser ( to convert string object into JSON objects ). For that, you will need a box called SimpleJSON. Download the compulsory jar files and configure its class way in the system .
Step 8) Declare an example of the JSONParser :
JSONParser parse = new JSONParser();
Step 9) Convert the string objects into JSON objects :
JSONObject jobj = (JSONObject)parse.parse(inline);
If you view the JSON structure, it will be something like this :
{
"results" : [
{
"place_id" : "ChIJ7cv00DwsDogRAMDACa2m4K8",
"types" : [ "locality", "political" ]
} ]
}
I would now like to get the corresponding values under the results range .
Step 10) First, convert the JSON aim into JSONArray object like this :
JSONArray jsonarr_1 = (JSONArray) jobj.get(“results”);
Step 11) Once the JSON objects are stored in the range, read the represent JSONArray objects, and convert it to JSON objects again so you get the elements within the results array. here is how you do it :
//Get data for Results array
for(int i=0;i
Let us dig a bit deep. 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
now we parse the JSON data award in the string format :
//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
here is the GitHub link to help you out get begin parsing datum from an API .