猿问

使用 GSON 反序列化 json 时间戳

我有一个 json 字符串,例如

{"start_time": "10:00 AM", "end_time": "11:00 PM"}

如果我使用 GSON 使用 POJO 反序列化,那么如您所见,这些将映射到我的类中的 String 变量。最终,我想使用用户提供的时间,看看它是否在范围内。我能想到的唯一方法是,每次我得到时间,然后我将这些字符串变量转换为对象(无论是 Joda 时间、日期、本地时间 .. 等),然后进行比较。

有没有更好的办法?我可以让 GSON 将字符串直接反序列化为时间对象吗?或者以某种方式保存在比较期间始终进行这些转换的步骤?或者我提出的方式真的是正确的设计?


米琪卡哇伊
浏览 378回答 3
3回答

ibeautiful

您可以使用GsonBuilder将时间解析为日期,指定日期格式:&nbsp; &nbsp; GsonBuilder gsonBuilder = new GsonBuilder();&nbsp; &nbsp; gsonBuilder.setDateFormat("HH:mm a");&nbsp; &nbsp; Gson gson = gsonBuilder.create();&nbsp; &nbsp; Pojo fromJson = gson.fromJson(<string>, Pojo.class);POJO 字段将如下所示(如果需要,请重命名):&nbsp; &nbsp; private Date start_time;&nbsp; &nbsp; private Date end_time;

DIEA

你对图书馆要求不高。您可以自己用纯 Java 编写该类,因为您只比较一天中的 24 小时。你可以这样:public class TimeKeeper implements Comparable<TimeKeeper> {&nbsp; &nbsp; byte startHour;&nbsp; &nbsp; byte startMinute;&nbsp; &nbsp; byte endHour;&nbsp; &nbsp; byte endMinute;&nbsp; &nbsp; public TimeKeeper(String start, String end) {&nbsp; &nbsp; &nbsp; &nbsp; startHour = parseHour(start);&nbsp; &nbsp; &nbsp; &nbsp; startMinute = parseMinute(start);&nbsp; &nbsp; &nbsp; &nbsp; endHour = parseHour(end);&nbsp; &nbsp; &nbsp; &nbsp; endMinute = parseMinute(end);&nbsp; &nbsp; }&nbsp; &nbsp; public byte parseHour(String time) {&nbsp; &nbsp; &nbsp; &nbsp; byte hour = Byte.valueOf(String.split(time, ":")[0]);&nbsp; &nbsp; &nbsp; &nbsp; if(time.contains("PM") {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; hour += 12;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return hour;&nbsp; &nbsp; }&nbsp; &nbsp; public byte parseMinute(String time) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return Byte.valueOf(String.valueOf(time, ":")[1].substring(0, 2));&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public int compareTo(TimeKeeper tk) {&nbsp; &nbsp; &nbsp; &nbsp; int diff = startHour - tk.startHour;&nbsp; &nbsp; &nbsp; &nbsp; if(diff == 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return startMinute - tk.startMinute;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return diff;&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答