MappingJackson2HttpMessageConverter 使用 Jackson 的 ObjectMapper 将 JSON 反序列化为 Pojos(或从 JSON 反序列化为 Maps/JsonNodes)。因此,一种方法是创建一个作为反序列化对象的 POJO。
如果预期时间值确实是“HH:MM”,其中“HH”实际上表示“一天中的小时 (0-23)”,而“MM”表示“小时中的分钟 (0-59)”,那么以下方法可以用。
将自定义 @JsonCreator 添加到您的支持 POJO:
public class TimeLeftPojo {
// The time pattern
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
// The checked property
private final boolean checked;
// The parsed time
private final LocalTime timeLeft;
// A creator that takes the string "HH:mm" as arg
@JsonCreator
public static TimeLeftPojo of(
@JsonProperty("timeLeft") String timeLeft,
@JsonProperty("checked") boolean checked) {
return new TimeLeftPojo(
LocalTime.parse(timeLeft, formatter), checked);
}
public TimeLeftPojo(final LocalTime timeLeft, final boolean checked) {
this.timeLeft = timeLeft;
this.checked = checked;
}
public LocalTime getTimeLeft() {
return timeLeft;
}
public long toMillisecondOfDay() {
return getTimeLeft().toSecondOfDay() * 1000;
}
public boolean isChecked() {
return checked;
}
}
然后反序列化开箱即用:
ObjectMapper mapper = new ObjectMapper();
// Changed the spelling from "cheked" to "checked"
String json = "{\"timeLeft\": \"10:00\", \"checked\": true}";
final TimeLeftPojo timeLeftPojo = mapper.readValue(json, TimeLeftPojo.class);
System.out.println(timeLeftPojo.toMillisecondOfDay());
输出将是:
36000000
@JsonCreator 的 JavaDoc 可以是 be found here。
请注意,时间模式是“HH:mm”,而不是原始查询中的“HH:MM”(“M”是月,而不是分钟)。