My First Post      My Facebook Profile      My MeOnShow Profile      W3LC Facebook Page      Learners Consortium Group      Job Portal      Shopping @Yeyhi.com

Pages










Monday, July 29, 2019

Parsing Json in Java using JsonParser

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:

 
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.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(int i=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
JSONObject jsonobj_1 = (JSONObject)jsonarray.get(i);
System.out.println(“Elements under results array”);
}

No comments:

Post a Comment