2017-04-11 18 views
0

我正在阅读JSON文件,取出值并做一些更改。写入JSONArray

基本上我给数组添加了一些值。之后,我想把它写回到一个文件中。当我写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"} 

     ] 
} 
+0

你能提供输入文件的内容是什么?或者至少有一个相关的片段 – 2017-04-11 16:47:08

+0

而且'预订'类的代码 – 2017-04-11 17:05:06

+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);