1import net.sf.json.JSONObject;
2import net.sf.json.JSONSerializer;
3import org.apache.commons.io.IOUtils;
4
5 public class JsonParsing {
6
7 public static void main(String[] args) throws Exception {
8 InputStream is =
9 JsonParsing.class.getResourceAsStream( "sample-json.txt");
10 String jsonTxt = IOUtils.toString( is );
11
12 JSONObject json = (JSONObject) JSONSerializer.toJSON( jsonTxt );
13 double coolness = json.getDouble( "coolness" );
14 int altitude = json.getInt( "altitude" );
15 JSONObject pilot = json.getJSONObject("pilot");
16 String firstName = pilot.getString("firstName");
17 String lastName = pilot.getString("lastName");
18
19 System.out.println( "Coolness: " + coolness );
20 System.out.println( "Altitude: " + altitude );
21 System.out.println( "Pilot: " + lastName );
22 }
23 }
24
1package com.howtodoinjava.demo.jsonsimple;
2
3import java.io.FileWriter;
4import java.io.IOException;
5
6import org.json.simple.JSONArray;
7import org.json.simple.JSONObject;
8
9public class WriteJSONExample
10{
11 @SuppressWarnings("unchecked")
12 public static void main( String[] args )
13 {
14 //First Employee
15 JSONObject employeeDetails = new JSONObject();
16 employeeDetails.put("firstName", "Lokesh");
17 employeeDetails.put("lastName", "Gupta");
18 employeeDetails.put("website", "howtodoinjava.com");
19
20 JSONObject employeeObject = new JSONObject();
21 employeeObject.put("employee", employeeDetails);
22
23 //Second Employee
24 JSONObject employeeDetails2 = new JSONObject();
25 employeeDetails2.put("firstName", "Brian");
26 employeeDetails2.put("lastName", "Schultz");
27 employeeDetails2.put("website", "example.com");
28
29 JSONObject employeeObject2 = new JSONObject();
30 employeeObject2.put("employee", employeeDetails2);
31
32 //Add employees to list
33 JSONArray employeeList = new JSONArray();
34 employeeList.add(employeeObject);
35 employeeList.add(employeeObject2);
36
37 //Write JSON file
38 try (FileWriter file = new FileWriter("employees.json")) {
39
40 file.write(employeeList.toJSONString());
41 file.flush();
42
43 } catch (IOException e) {
44 e.printStackTrace();
45 }
46 }
47}
48