-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCarDeletion.java
59 lines (52 loc) · 2.19 KB
/
CarDeletion.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
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class CarDeletion {
public static void deleteCar(String filePath, int carId) {
try {
// Read the JSON file
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(filePath));
// Handle both single object and array scenarios
JSONObject jsonObject;
JSONArray carsArray;
if (obj instanceof JSONObject) {
jsonObject = (JSONObject) obj;
carsArray = (JSONArray) jsonObject.get("Cars"); // Assuming "Cars" is the key for the car data array
} else {
carsArray = (JSONArray) obj; // Treat the entire object as an array
}
// Find the car to delete
JSONObject carToDelete = null;
for (Object carObject : carsArray) {
JSONObject car = (JSONObject) carObject;
if ((long) car.get("ID") == carId) {
carToDelete = car;
break;
}
}
// Remove the car if found
if (carToDelete != null) {
carsArray.remove(carToDelete);
// Write the updated JSON data back to the file
try (FileWriter fileWriter = new FileWriter(filePath)) {
if (carsArray.isEmpty()) {
// Handle empty array case (if the last car was deleted)
fileWriter.write("{}"); // Write an empty object
} else {
fileWriter.write(carsArray.toJSONString());
}
System.out.println("Car with ID " + carId + " deleted successfully.");
}
} else {
System.out.println("Car with ID " + carId + " not found.");
}
} catch (IOException | ParseException e) {
System.err.println("Error deleting car: " + e.getMessage());
}
}
}