Java 8 LocalDate Jackson格式對于java.util.Date,當(dāng)我這樣做@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy")
private Date dateOfBirth;然后在我發(fā)送的JSON請求中{ {"dateOfBirth":"01/01/2000"} }有用。我應(yīng)該如何為Java 8的LocalDate字段執(zhí)行此操作?我試過了@JsonDeserialize(using = LocalDateDeserializer.class) @JsonSerialize(using = LocalDateSerializer.class) private LocalDate dateOfBirth;它沒用。有人可以讓我知道這是正確的方法嗎?以下是依賴項(xiàng)<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>jaxrs-api</artifactId>
<version>3.0.9.Final</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>com.wordnik</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.3.10</version>
</dependency>
<dependency>
3 回答

臨摹微笑
TA貢獻(xiàn)1982條經(jīng)驗(yàn) 獲得超2個贊
它們無需導(dǎo)入額外的jsr310模塊:
@JsonDeserialize(using = LocalDateDeserializer.class) @JsonSerialize(using = LocalDateSerializer.class) private LocalDate dateOfBirth;
解串器:
public class LocalDateDeserializer extends StdDeserializer<LocalDate> { private static final long serialVersionUID = 1L; protected LocalDateDeserializer() { super(LocalDate.class); } @Override public LocalDate deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { return LocalDate.parse(jp.readValueAs(String.class)); }}
串行:
public class LocalDateSerializer extends StdSerializer<LocalDate> { private static final long serialVersionUID = 1L; public LocalDateSerializer(){ super(LocalDate.class); } @Override public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider sp) throws IOException, JsonProcessingException { gen.writeString(value.format(DateTimeFormatter.ISO_LOCAL_DATE)); }}

富國滬深
TA貢獻(xiàn)1790條經(jīng)驗(yàn) 獲得超9個贊
ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JavaTimeModule()); mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
對我來說很好。
添加回答
舉報
0/150
提交
取消