在本文中,我們將探討如何使用Jackson 格式化java.time.LocalDate在Java 8 中。
使用時Java 8 的 LocalDate 字段,嘗試使用與 java.util.Date 相同的註釋可能不會產生所需的結果。
@JsonDeserialize(using = LocalDateDeserializer.class) @JsonSerialize(using = LocalDateSerializer.class) private LocalDate dateOfBirth;
至正確格式化LocalDate,應執行以下步驟採取:
添加jackson-datatype-jsr310相依性:
<dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> <version>2.4.0</version> </dependency>
為 ObjectMapper 建立 ContextResolver:
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.Provider; @Provider public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> { private final ObjectMapper MAPPER; public ObjectMapperContextResolver() { MAPPER = new ObjectMapper(); MAPPER.registerModule(new JavaTimeModule()); MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); } @Override public ObjectMapper getContext(Class<?> type) { return MAPPER; } }
註冊資源類別中的ObjectMapperContextResolver:
@Path("person") public class LocalDateResource { @GET @Produces(MediaType.APPLICATION_JSON) public Response getPerson() { Person person = new Person(); person.birthDate = LocalDate.now(); return Response.ok(person).build(); } @POST @Consumes(MediaType.APPLICATION_JSON) public Response createPerson(Person person) { return Response.ok( DateTimeFormatter.ISO_DATE.format(person.birthDate)).build(); } public static class Person { public LocalDate birthDate; } }
您現在可以透過發出以下HTTP 請求來測試格式:
# Get person curl -v http://localhost:8080/api/person # Create person curl -v -POST -H "Content-Type:application/json" -d "{\"birthDate\":\"2015-03-01\"}" http://localhost:8080/api/person
回覆:
{"birthDate":"2015-03-01"}
以上是如何使用 Jackson 正確格式化 Java 8 的 LocalDate?的詳細內容。更多資訊請關注PHP中文網其他相關文章!