Quantcast
Channel: W3LC - World Wide Web Learners Consortium
Viewing all articles
Browse latest Browse all 108

Parsing Json in Java using JsonParser

$
0
0
You can use one of the many available Json Parser for the purpose. I have personally used following in simple applications. You can refer this tutorial:

 
importorg.json.simple.JSONArray;
importorg.json.simple.JSONObject;
importorg.json.simple.parser.JSONParser;
importorg.json.simple.parser.ParseException;



 
You might need to install dependencies first:

In case you are on maven, use following to set a proper environment for the compiler, in order to recognize the JSON's classes. If you want to built your project via Maven, you should add the following dependency to your pom.xml:
1
2
3
4
5
<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1</version>
</dependency>
Otherwise, you have to add the newest version of json-simple-1.1.1.jar in your CLASSPATH.

First you need to Declare an instance of the JSONParser:
 JSONParser parse = new JSONParser(); 

Then, Convert the string objects into JSON objects:
 JSONObject jobject = (JSONObject)parse.parse(inline); 
If you view the JSON structure, it will be something like this:
{
"results" : [
      {
"place_id" : "aa1123",
"types" : [ "locality", "book" ]
      } ]
}

Then you can convert the JSON object into JSONArray 
JSONArray jsonarray = (JSONArray) jobj.get(“results”); 

Now you can use as per your need, for eg.
get the elements within the results array. Here is how you do it:
//Get data for Results array
for(inti=0;i<jsonarray.size();i++)
{
//Store the JSON objects in an array
//Get the index of the JSON object and print the values as per the index
JSONObjectjsonobj_1= (JSONObject)jsonarray.get(i);
System.out.println(“Elementsunderresultsarray”);
}


Viewing all articles
Browse latest Browse all 108

Trending Articles