如何从动态更新的json获取最新数据?

时间:2013-02-15 13:43:57

标签: java json

聊天哪个内容我要解析。我得到了它的网址.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中解析新记录的最佳实践?事实上,我不知道如何控制它的更新,但每秒读取它并将结果输出到输出将导致我认为数据重复。

2 个答案:

答案 0 :(得分:1)

你需要以某种方式对这些数据进行切片...当文件增长时,为了不让你的GSON解析速度慢,我认为你需要对文件进行预处理,切换一次性数据。我会做类似的事情:

  • 首次执行:完全解析文件并存储第一个id,因为它是最新的数据;
  • 第二次执行(和其他):读取文件并将其存储在StringBuilder中。使用获得的字符串,对可处理的数据进行切片,因为您之前存储了id。此ID将显示您需要开始切片的位置。使用新数据,解析GSON并再次存储第一个ID。

您可以使用此创建代码来执行切片并适应我在下面所述的想法:

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>与日期字符串一起使用