Reputation: 9141
I want to store chat history in a JSON Object, one object for each conversation, within this object i want to have an Array with all the messages.
Like this:
{"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"}
]
}
My current method looks like this: (the string channel
contains the conversation id illustrated above with 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);
}
But for some reason the method is not appending to the object it is overwriting what was previously there.
Any ideas?
EDIT
I am using the simple json lib: json-simple-1.1.1.jar
Upvotes: 1
Views: 6390
Reputation: 9
A valid JSON data representation won't duplicate keys in the same nesting level. Keeping in mind that only numbers, strings, null, objects and arrays are valid JSON primitives, you have some structure like:
[
{
...
"id_str" : "foo",
...
},
{
...
"id_str" : "bar",
...
},
...
]
Which is an array of JSON objects. In this case, you'd have to index the 4th element of the array and then index the "id_str" attribute of that object. Check the documentation of whatever JSON library you're using to decode the data to figure out how to do that.
Upvotes: 0
Reputation: 30875
I am not familiar with the jason-simple API but you should create a new instance of JSONObject
for each item.
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);
}
}
Upvotes: 1