我在SO上读到了几个关于java.time.LocalDateTime
和JSON属性之间序列化和反序列化的问题和答案,但是我似乎无法让它正常工作。
我已经成功配置了我的Spring Boot应用程序,使其以我所需的格式(YYY-MM-dd HH:mm
)返回日期,但我无法接受以此格式在JSON中传递的值。
这是我迄今为止所做的所有事情:
添加了jsr310
的Maven依赖:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
在我的主类中指定了jsr310
:
@EntityScan(basePackageClasses = { App.class, Jsr310JpaConverters.class })
禁用在application.properties
中的时间戳序列化:
spring.jackson.serialization.write_dates_as_timestamps=false
这是我的日期时间实体映射:
@Column(name = "start_date")
@DateTimeFormat(iso = DateTimeFormat.ISO.TIME)
@JsonFormat(pattern = "YYYY-MM-dd HH:mm")
private LocalDateTime startDate;
在我的数据库中,我将这个日期以以下格式存储为时间戳:2016-12-01T23:00:00+00:00
。
当我通过控制器访问此实体时,它返回具有正确开始日期格式的JSON。但是,当我尝试以YYYY-MM-dd HH:mm
格式进行发布和反序列化时,我会收到以下异常:
{
"timestamp": "2016-10-30T14:22:25.285+0000",
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.http.converter.HttpMessageNotReadableException",
"message": "Could not read document: Can not deserialize value of type java.time.LocalDateTime from String \"2017-01-01 20:00\": Text '2017-01-01 20:00' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {MonthOfYear=1, WeekBasedYear[WeekFields[SUNDAY,1]]=2017, DayOfMonth=1},ISO resolved to 20:00 of type java.time.format.Parsed\n at [Source: java.io.PushbackInputStream@679a734d; line: 6, column: 16] (through reference chain: com.gigsterous.api.model.Event[\"startDate\"]); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not deserialize value of type java.time.LocalDateTime from String \"2017-01-01 20:00\": Text '2017-01-01 20:00' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {MonthOfYear=1, WeekBasedYear[WeekFields[SUNDAY,1]]=2017, DayOfMonth=1},ISO resolved to 20:00 of type java.time.format.Parsed\n at [Source: java.io.PushbackInputStream@679a734d; line: 6, column: 16] (through reference chain: com.gigsterous.api.model.Event[\"startDate\"])",
"path": "/api/events"
}
我知道关于这个话题有很多答案,但是遵循它们并尝试了几个小时后都没有帮助我找出我做错了什么,所以如果有人能指出我漏掉了什么,我将非常感激。谢谢对此的任何建议!
编辑:这些都是涉及到这个过程的所有类:
Repository:
@Repository
public interface EventRepository extends PagingAndSortingRepository<Event, Long> {
}
控制器:
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Event> createEvent(@RequestBody Event event) {
return new ResponseEntity<>(eventRepo.save(event), HttpStatus.CREATED);
}
我的JSON请求负载:
{
"name": "Test",
"startDate": "2017-01-01 20:00"
}
事件:
@Entity
@Table(name = "events")
@Getter
@Setter
public class Event {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "event_id")
private long id;
@Column(name = "name")
private String name;
@Column(name = "start_date")
@DateTimeFormat(iso = DateTimeFormat.ISO.TIME)
@JsonFormat(pattern = "YYYY-MM-dd HH:mm")
private LocalDateTime startDate;
}