In this post, I will explain how to parse JSON data using Gson framework.
Each element whether start and end of the object, start and end of array, field name and field values are considered as tokens and are represented by JsonToken enums.
The Gson framework parses the json data as a stream of tokens.
For this post, we will use the below json data.
jsondata.json
{
"firstName": "Duke",
"lastName": "Java",
"age": 18,
"streetAddress": "100 Internet Dr",
"city": "JavaTown",
"state": "JA",
"postalCode": "12345",
"phoneNumbers": [
{ "Mobile": "111-111-1111" },
{ "Home": "222-222-2222" }
]
}
Below is the complete code
Main code
1 import java.io.File;
2 import java.io.FileReader;
3 import java.io.IOException;
4
5 import com.google.gson.stream.JsonReader;
6 import com.google.gson.stream.JsonToken;
7
8 public class GsonDemo3 {
9 public static void main(String[] args) throws IOException {
10 File file = new File("jsondata.json");
11 FileReader fr = new FileReader(file);
12 JsonReader jr = new JsonReader(fr);
13 boolean done = true;
14 while(done) {
15 JsonToken jsonToken = jr.peek();
16 switch(jsonToken) {
17 case BEGIN_OBJECT: System.out.println("----Start of the object----");
18 jr.beginObject();
19 break;
20 case END_OBJECT: System.out.println("----End of the object----");
21 jr.endObject();
22 break;
23 case BEGIN_ARRAY: System.out.println("----Start of an array----");
24 jr.beginArray();
25 break;
26 case END_ARRAY: System.out.println("----End of an array----");
27 jr.endArray();
28 break;
29 case NAME: String name = jr.nextName();
30 System.out.println(name);
31 break;
32 case STRING: String value1 = jr.nextString();
33 System.out.println(value1);
34 break;
35 case NUMBER: int value2 = jr.nextInt();
36 System.out.println(value2);
37 break;
38 case BOOLEAN: boolean value3 = jr.nextBoolean();
39 System.out.println(value3);
40 break;
41 case END_DOCUMENT: done = false;
42 break;
43 }
44 }
45 jr.close();
46 }
47 }
At line 12, we create an instance of JsonReader which takes an instance of java.io.FileReader as an argument.
In the while loop, we retrieve the next token by calling the “peek” method. Similar to method name, the peek method doesn’t move to the next token, it looks ahead
to know what the next token is, without moving to that token.
To move to the next token, we use nextXXX and beginXXX methods, as shown at line 18, 21, 24, 27, 29, 32, and 38.
Below is the output
Output
—-Start of the object—-
firstName
Duke
lastName
Java
age
18
streetAddress
100 Internet Dr
city
JavaTown
state
JA
postalCode
12345
phoneNumbers
—-Start of an array—-
—-Start of the object—-
Mobile
111-111-1111
—-End of the object—-
—-Start of the object—-
Home
222-222-2222
—-End of the object—-
—-End of an array—-
—-End of the object—-