- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCreateJsonExample.java
More file actions
Latest commit
50 lines (45 loc) · 1.73 KB
/
Copy pathCreateJsonExample.java
File metadata and controls
50 lines (45 loc) · 1.73 KB
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
// import com.google.gson.Gson;
// import com.google.gson.GsonBuilder;
importjava.io.FileWriter;
importjava.io.IOException;
importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.List;
importjava.util.Map;
importorg.json.simple.JSONArray;
importorg.json.simple.JSONObject;
publicclassCreateJsonExample {
publicstaticvoidmain(String[] args) {
// Create a Map to represent the JSON structure
Map<String, Object> jsonMap = newHashMap<>();
JSONArrayjsonArray = newJSONArray();
// Add the name and age properties
jsonMap.put("name", "John");
jsonMap.put("age", 30);
Map<String, Object> jsonMap2 = newHashMap<>();
jsonMap2.put("name", "Johnhn");
jsonMap2.put("age", 32);
// Create a List for the cars property
List<String> carsList = newArrayList<>();
carsList.add("Ford");
carsList.add("BMW");
carsList.add("Fiat");
// Add the cars property to the Map
jsonMap.put("cars", carsList);
jsonMap2.put("cars" , carsList);
// Convert the JSON map to a JSON string
// Gson gson = new GsonBuilder().setPrettyPrinting().create();
// String json = gson.toJson(jsonMap);
JSONObjectjsonObject1 = newJSONObject(jsonMap);
JSONObjectjsonObject2 = newJSONObject(jsonMap2);
jsonArray.add(jsonObject1);
jsonArray.add(jsonObject2);
// Write the JSON string to a file
try (FileWriterwriter = newFileWriter("E:/OOP/javaProject/test.json")) {
writer.write(jsonArray.toString());
System.out.println("JSON written to file successfully.");
} catch (IOExceptione) {
e.printStackTrace();
}
}
}