-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathParseJSONUsingGSON.java
68 lines (55 loc) · 2.19 KB
/
ParseJSONUsingGSON.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package com.coderolls.JSONExample;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
/**
* A program to parse JSON strin in Java using Gson
* @author Gaurav Kukade at coderolls.com
*/
public class ParseJSONUsingGSON {
public static void main(String[] args) {
//take json as string
String jsonString = "{"
+ " \"name\": \"coderolls\","
+ " \"type\": \"blog\","
+ " \"address\": {"
+ " \"street\": \"1600 Pennsylvania Avenue NW\","
+ " \"city\": \"Washington\","
+ " \"state\": \"DC\""
+ " },"
+ " \"employees\": ["
+ " {"
+ " \"firstName\": \"John\","
+ " \"lastName\": \"Doe\""
+ " },"
+ " {"
+ " \"firstName\": \"Anna\","
+ " \"lastName\": \"Smith\""
+ " },"
+ " {"
+ " \"firstName\": \"Peter\","
+ " \"lastName\": \"Jones\""
+ " }"
+ " ]"
+ "}";
System.out.println("Parsing the json string in java using Gson......\n");
Gson gson = new Gson();
//get json object from the json string
JsonObject coderollsJsonObject = gson.fromJson(jsonString, JsonObject.class);
//now we can access the values
String name = coderollsJsonObject.get("name").getAsString();
System.out.println("Name: "+name+"\n");
//we can get the JSON object present as value of any key in the parent JSON
JsonObject addressJsonObject = coderollsJsonObject.get("address").getAsJsonObject();
//access the values of the addressJSONObject
String street = addressJsonObject.get("street").getAsString();
System.out.println("Street: "+street+"\n");
//we can get the json array present as value of any key in the parent JSON
JsonArray employeesJsonArray = coderollsJsonObject.get("employees").getAsJsonArray();
System.out.println("Printing the employess json array: \n"+employeesJsonArray.toString()+"\n");
//we can get individual json object at an index from the employeesJSONArray
JsonObject employeeJsonObject = employeesJsonArray.get(0).getAsJsonObject();
String firstName = employeeJsonObject.get("firstName").getAsString();
System.out.println("First Name of the employee at index 0: "+firstName);
}
}