-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathParseJSONUsingJsonSimple.java
73 lines (60 loc) · 2.36 KB
/
ParseJSONUsingJsonSimple.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
69
70
71
72
73
package com.coderolls.JSONExample;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
/**
* A program to parse JSON strin in Java using json-simple
* @author Gaurav Kukade at coderolls.com
*/
public class ParseJSONUsingJsonSimple {
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 json-simple......\n");
JSONParser parser = new JSONParser();
JSONObject coderollsJSONObject = new JSONObject();
try {
coderollsJSONObject = (JSONObject) parser.parse(jsonString);
} catch (ParseException e) {
e.printStackTrace();
}
//now we can access the values
String name = (String) coderollsJSONObject.get("name");
System.out.println("Name: "+name+"\n");
//we can get the JSON object present as value of any key in the parent JSON
JSONObject addressJSONObject = (JSONObject) coderollsJSONObject.get("address");
//access the values of the addressJSONObject
String street = (String) addressJSONObject.get("street");
System.out.println("Street: "+street+"\n");
//we can get the json array present as value of any key in the parent JSON
JSONArray employeesJSONArray = (JSONArray) coderollsJSONObject.get("employees");
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 = (JSONObject) employeesJSONArray.get(0);
String firstName = (String) employeeJSONObject.get("firstName");
System.out.println("First Name of the employee at index 0: "+firstName);
}
}