我想将聊天历史记录存储在一个 JSON 对象中,每个对话一个对象,在这个对象中我想有一个包含所有消息的数组。
像这样:
{"Channel_123":[
{"from":"john","to":"bill", "msg":"Hello", "time":"09:57"},
{"from":"bill","to":"john", "msg":"Hey John", "time":"09:58"}
]
}, {"Channel_234":[
{"from":"bob","to":"judy", "msg":"Hello", "time":"10:37"},
{"from":"judy","to":"bob", "msg":"Hey!", "time":"10:38"}
]
}
我当前的方法如下所示:(字符串 channel
包含上面所示的对话 ID Channel_234
JSONObject obj = new JSONObject();
JSONObject msgObj = new JSONObject();
public void addMessage(String from, String to, String msg, String time, String channel) {
try {
msgObj.put("from", from);
msgObj.put("to", to);
msgObj.put("msg", msg);
msgObj.put("time", time);
obj.put(channel, array);
} catch (Exception ex) {
System.out.println(ex.getStackTrace());
logger.log(Level.SEVERE, "Exception: ", ex);
}
System.out.println(obj);
}
但由于某种原因,该方法没有附加到对象,而是覆盖了之前的内容。
有什么想法吗?
编辑
我正在使用简单的 json 库:json-simple-1.1.1.jar
最佳答案
我不熟悉 jason-simple API,但您应该为每个项目创建一个新的 JSONObject
实例。
private JSONObject createMesssage(String form, String to, String msg, String time) throws Exception {
JSONObject jsonMessage= new JSONObject();
jsonMessage.put("from", from);
jsonMessage.put("to", to);
jsonMessage.put("msg", msg);
jsonMessage.put("time", time);
return jsonMessage;
}
JSONObject obj = new JSONObject();
private void addMessage(String channel, JSonObject messsage) throw Exception {
obj.put(channel, message);
}
public void saveMessage(String form, String to, String msg, String time, Striing channel ) {
try {
addMessage(chanell,createMessage(form,to,msg,time));
} catch (Exception ex) {
logger.log(Level.SEVERE, "Exception: ", ex);
}
}
关于Java:将 JSON 对象附加到 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20346790/