Thursday, 11 September 2014

Java JSON parser Example

Example of JSON parsing

As we mentioned, we will show how we can parse a json file, so we will make our own .json file. This file is named jsonTestFile.jsonand has the next structure:
jsonTestFile.json:
{
 "id": 1,
        "firstname": "Katerina",
 "languages": [
  { "lang":"en" , "knowledge":"proficient" }, 
  { "lang":"fr" , "knowledge":"advanced" }, 
 ]
 "job":{
                "site":"www.javacodegeeks.com",
                "name":"Java Code Geeks",
        }  
}
Now create a java file in your project, named JsonParseTest. Then paste the following code.
JsonParseTest.java:
01package com.javacodegeeks.javabasics.jsonparsertest;
02
03import java.io.FileNotFoundException;
04import java.io.FileReader;
05import java.io.IOException;
06import java.util.Iterator;
07
08import org.json.simple.JSONArray;
09import org.json.simple.JSONObject;
10import org.json.simple.parser.JSONParser;
11import org.json.simple.parser.ParseException;
12
13public class JsonParseTest {
14
15    private static final String filePath = "C:\\Users\\katerina\\Desktop\\jsonTestFile.json";
16     
17    public static void main(String[] args) {
18
19        try {
20            // read the json file
21            FileReader reader = new FileReader(filePath);
22
23            JSONParser jsonParser = new JSONParser();
24            JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
25
26            // get a String from the JSON object
27            String firstName = (String) jsonObject.get("firstname");
28            System.out.println("The first name is: " + firstName);
29
30            // get a number from the JSON object
31            long id =  (long) jsonObject.get("id");
32            System.out.println("The id is: " + id);
33
34            // get an array from the JSON object
35            JSONArray lang= (JSONArray) jsonObject.get("languages");
36             
37            // take the elements of the json array
38            for(int i=0; i<lang.size(); i++){
39                System.out.println("The " + i + " element of the array: "+lang.get(i));
40            }
41            Iterator i = lang.iterator();
42
43            // take each value from the json array separately
44            while (i.hasNext()) {
45                JSONObject innerObj = (JSONObject) i.next();
46                System.out.println("language "+ innerObj.get("lang") +
47                        " with level " + innerObj.get("knowledge"));
48            }
49            // handle a structure into the json object
50            JSONObject structure = (JSONObject) jsonObject.get("job");
51            System.out.println("Into job structure, name: " + structure.get("name"));
52
53        } catch (FileNotFoundException ex) {
54            ex.printStackTrace();
55        } catch (IOException ex) {
56            ex.printStackTrace();
57        } catch (ParseException ex) {
58            ex.printStackTrace();
59        } catch (NullPointerException ex) {
60            ex.printStackTrace();
61        }
62
63    }
64
65}
Now lets explain the code above. After we create an instance of JSONParser, we create a JSONObject by parsing the FileReader of our .json file. This JSONObject contains a collection of key-value pairs, from which we can get every value of the json file. To retrieve primitive objects, get() method of the JSONObject's instance is called, defining the specified key as an argument. It is important to add the suitable cast to the method. For array types in json file, JSONArray is used that represents an ordered sequence of values. As you can notice in the code, an Iterator should be used in order to take each value of the json array. A structure in the json file, signs the creation of a new JSONObject in order to retrieve the values.
You can see the output of the execution below.

No comments:

Post a Comment