jackson-databind包默認不支持jdk8新的日期類型LocalDate。該問題處理方式以下:java
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.8</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.module</groupId> <artifactId>jackson-module-parameter-names</artifactId> <version>2.8.8</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jdk8</artifactId> <version>2.8.8</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> <version>2.8.8</version> </dependency>
package com.fasterxml.jackson; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.fasterxml.jackson.module.paramnames.ParameterNamesModule; import org.junit.Assert; import org.junit.Test; import java.io.IOException; import java.time.LocalDate; public class JacksonTest { @Test public void test() throws IOException { ClassA a = new ClassA(); a.setName("name1"); a.setLocalDate(LocalDate.now()); ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new ParameterNamesModule()) .registerModule(new Jdk8Module()) .registerModule(new JavaTimeModule()); String json = mapper.writeValueAsString(a); System.out.println(json); ClassA a2 = mapper.readValue(json, ClassA.class); Assert.assertEquals(a.getName(), a2.getName()); Assert.assertEquals(a.getLocalDate(), a2.getLocalDate()); } static class ClassA { private String name; @JsonFormat(pattern = "yyyy-MM-dd") private LocalDate localDate; public LocalDate getLocalDate() { return localDate; } public void setLocalDate(LocalDate localDate) { this.localDate = localDate; } public String getName() { return name; } public void setName(String name) { this.name = name; } } }