我正在阅读JSON文件,取出值并进行一些更改。
基本上我在数组中添加了一些值。之后我想把它写回一个文件。当我将JSONArray
写回文件时写为字符串而不是JSONArray
对象。我怎么写得好呢?
在以下代码中我写入JSON文件:
JSONArray rooms = (JSONArray) jsonObject.get("rooms");
for (int i = 0; i < rooms.size(); i++) {
JSONObject room = (JSONObject) rooms.get(i);
String roomName = (String) room.get("roomName");
System.out.println("RoomName: " + roomName + " Size: " + "O: " + oldRoomListSize.get(roomName) + " N: " + roomList.get(roomName).getRoomBook().size());
if(oldRoomListSize.get(roomName) < roomList.get(roomName).getRoomBook().size()) {
int n = roomList.get(roomName).getRoomBook().size() - oldRoomListSize.get(roomName);
for (int j = n; j > 0; j--) {
int lenght = roomList.get(roomName).getRoomBook().size();
JSONArray schedule = (JSONArray) room.get("schedule");
Reservation r = roomList.get(roomName).getRoomBook().get(lenght-j);
schedule.add(r);
}
}
}
fileWriter.write(jsonObject.toJSONString());
fileWriter.close();
正如您所看到的,正在被写为字符串,当我想要阅读它时它会给我带来问题。
"schedule":["{Day: 1 - Start Time: 10}"]
文件阅读器:
JSONArray schedule = (JSONArray) room.get("schedule");
for (int j = 0; j < schedule.size(); j++) {
JSONObject s = (JSONObject) schedule.get(j);
String day = (String) s.get("day");
String startTime = (String) s.get("startTime");
lRoom.setRoomBook(Integer.parseInt(day), Integer.parseInt(startTime));
}
错误:java.lang.ClassCastException:无法强制转换java.lang.String to org.json.simple.JSONObject
在向数组输入新值(引入日期和开始时间)后发生错误。它写成字符串,当我再次尝试阅读时,给我一个错误,说我无法解析它,因为阵列上有一个字符串。
输入文件:
{
"rooms":[
{"maxOccupants":"10",
"schedule":[{"startTime":"1","day":"10"},{"startTime":"20","day":"20"},{"startTime":"11","day":"122017"}],
"tv":"false",
"mobilePhone":"false",
"projector":"true",
"buildID":"1",
"floor":"2",
"roomName":"room1"},
{"maxOccupants":"4",
"schedule":[{"startTime":"10","day":"1"},{"startTime":"11","day":"122017"},{"startTime":"11","day":"15"}],
"tv":"false",
"mobilePhone":"false",
"projector":"false",
"buildID":"1",
"floor":"2",
"roomName":"room2"},
{"maxOccupants":"5",
"schedule":[{"startTime":"1","day":"10"},{"startTime":"11","day":"122017"}],
"tv":"false",
"mobilePhone":"false",
"projector":"true",
"buildID":"2",
"floor":"3",
"roomName":"room3"}
]
}
答案 0 :(得分:1)
问题解决了!我没有创建JSONObject,因此我将一个直接对象引入JSON数组,并强制将对话转换为String。
以下是问题的解决方法:
JSONObject jsonObj = new JSONObject();
String startTime = String.valueOf(r.getStartTime());
String day = String.valueOf(r.getDay());
jsonObj.put("startTime", startTime);
jsonObj.put("day", day);
schedule.add(jsonObj);