3 回答
TA贡献1874条经验 获得超12个赞
我认为你工作太努力了,没有得到你想要的。有一种更简单的方法,无需编写自己的反序列化器。看看这个问题。本质上它看起来像
@JsonFormat(shape= JsonFormat.Shape.STRING, pattern="EEE MMM dd HH:mm:ss Z yyyy")
@JsonProperty("created_at")
ZonedDateTime created_at;
而你只是戴上你自己的面具。另外,我曾经有一个任务是解析未知格式的日期,本质上我需要解析任何有效的日期。这是一篇描述如何实现它的想法的文章:Java 8 java.time package: parsing any string to date。你可能会发现它很有用
TA贡献1851条经验 获得超4个赞
当您使用java.time.*类并且Jackson最好从JavaTimeModule来自jackson-datatype-jsr310模块的注册开始。我们可以扩展它并使用提供的模式注册序列化程序,如下例所示:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class JsonApp {
public static void main(String[] args) throws Exception {
ObjectMapper mapperIso = createObjectMapper("yyyy-MM-dd");
ObjectMapper mapperCustom0 = createObjectMapper("yyyy/MM/dd");
ObjectMapper mapperCustom1 = createObjectMapper("MM-dd-yyyy");
System.out.println(mapperIso.writeValueAsString(new Time()));
System.out.println(mapperCustom0.writeValueAsString(new Time()));
System.out.println(mapperCustom1.writeValueAsString(new Time()));
}
private static ObjectMapper createObjectMapper(String pattern) {
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(pattern)));
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(javaTimeModule);
return mapper;
}
}
class Time {
private LocalDate now = LocalDate.now();
public LocalDate getNow() {
return now;
}
public void setNow(LocalDate now) {
this.now = now;
}
@Override
public String toString() {
return "Time{" +
"now=" + now +
'}';
}
}
Aboce 代码打印:
{"now":"2019-02-24"}
{"now":"2019/02/24"}
{"now":"02-24-2019"}
添加回答
举报