-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathParseJSONUsingJSONJava.java
67 lines (53 loc) · 2.07 KB
/
ParseJSONUsingJSONJava.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
package com.coderolls.JSONExample;
import org.json.JSONArray;
import org.json.JSONObject;
/**
* A program to parse JSON strin in Java using json-simple
* @author Gaurav Kukade at coderolls.com
*/
public class ParseJSONUsingJSONJava {
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-Java......\n");
//add jsonString to the constructor
JSONObject coderollsJSONObject = new JSONObject(jsonString);
//now we can access the values
String name = coderollsJSONObject.getString("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 = coderollsJSONObject.getJSONObject("address");
//access the values of the addressJSONObject
String street = addressJSONObject.getString("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 = coderollsJSONObject.getJSONArray("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 = employeesJSONArray.getJSONObject(0);
String firstName = employeeJSONObject.getString("firstName");
System.out.println("First Name of the employee at index 0: "+firstName);
}
}