聊天哪个内容我要解析。我得到了它的网址.json。所以它看起来像:
{"messages":[
{"id":"111111","uid":"22222","name":"User","message":"Message","date":"2013-02-15 17:21:54","chatId":"111"},
{"id":"111111","uid":"22222","name":"User","message":"Message","date":"2013-02-15 17:21:54","chatId":"111"},
{"id":"111111","uid":"22222","name":"User","message":"Message","date":"2013-02-15 17:21:54","chatId":"111"}
]}
但是这个json有一些限制,我认为大约有20到30个记录。一开始就添加了新记录。它看起来像:
{"messages":[
{"id":"222222","uid":"33333","name":"User","message":"Message","date":"2013-02-15 18:21:59","chatId":"111"},
{"id":"111111","uid":"22222","name":"User","message":"Message","date":"2013-02-15 17:21:54","chatId":"111"},
{"id":"111111","uid":"22222","name":"User","message":"Message","date":"2013-02-15 17:21:55","chatId":"111"}
]}
.......
{"messages":[
{"id":"333333","uid":"44444","name":"User","message":"Message","date":"2013-02-15 19:13:34","chatId":"111"},
{"id":"222222","uid":"33333","name":"User","message":"Message","date":"2013-02-15 18:21:59","chatId":"111"},
{"id":"111111","uid":"22222","name":"User","message":"Message","date":"2013-02-15 17:21:54","chatId":"111"}
]}
我会通过GSON或JSON Java读取这个json并放置到任何输出,这没关系:)
但是有没有关于如何在动态更新的json中解析新记录的最佳实践?事实上,我不知道如何控制它的更新,但每秒读取它并将结果输出到输出将导致我认为数据重复。
答案 0 :(得分:1)
你需要以某种方式对这些数据进行切片...当文件增长时,为了不让你的GSON解析速度慢,我认为你需要对文件进行预处理,切换一次性数据。我会做类似的事情:
您可以使用此创建代码来执行切片并适应我在下面所述的想法:
String data = "{\"messages\":[" +
"{\"id\":\"333333\",\"uid\":\"44444\",\"name\":\"User\",\"message\":\"Message\",\"date\":\"2013-02-15 19:13:34\",\"chatId\":\"111\"}," +
"{\"id\":\"222222\",\"uid\":\"33333\",\"name\":\"User\",\"message\":\"Message\",\"date\":\"2013-02-15 18:21:59\",\"chatId\":\"111\"}," +
"{\"id\":\"111111\",\"uid\":\"22222\",\"name\":\"User\",\"message\":\"Message\",\"date\":\"2013-02-15 17:21:54\",\"chatId\":\"111\"}" +
"]}";
String lastId = "111111";
int sliceUntil = data.indexOf( "{\"id\":\"" + lastId + "\"" );
// since your disposable data is in the "tail" you your file,
// you just need to get the valid data (the data until the "last id")
// and add the chars "]" and "}" to close your JSON
String newData = data.substring( 0, sliceUntil ) + "]}";
System.out.println( newData );
答案 1 :(得分:0)
每封邮件都有唯一的“日期”,因此您只需创建Map<Date, Message>
,即可使用所有不存在的元素进行更新。或者,如果您不需要时间排序,则可以将Map<String, Message>
与日期字符串一起使用