gpt4 book ai didi

java - 写入 JSONArray

转载 作者:行者123 更新时间:2023-12-02 13:27:07 27 4
gpt4 key购买 nike

我正在读取 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));
}

Error: java.lang.ClassCastException: java.lang.String cannot be cast 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"}

]
}

最佳答案

问题解决了!我没有创建 JSONObject,因此我直接向 JSON Array 引入一个对象,并强制与 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);

关于java - 写入 JSONArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43350620/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com