2
我創建了一個採用事件表單對象的Spring引導控制器。將序列化的HTML時間字段轉換爲java.time.LocalTime
@RestController
@RequestMapping("/Event")
public class EventController {
@RequestMapping(value = "/create", method = RequestMethod.POST)
private synchronized List<Event> createEvent(Event inEvent) {
log.error("create called with event: " + inEvent);
create(inEvent);
return listAll();
}
}
Event類看起來像這樣(省略getter/setter方法)
public final class Event {
private Integer id;
private Integer periodId;
private String name;
@DateTimeFormat(pattern = "dd/MM/yyyy")
private LocalDate eventDate;
private LocalTime startTime;
private LocalTime endTime;
private Integer maxParticipants;
private String status;
private String eventType;
}
我得到的開始時間Spring的類型不匹配錯誤和endTime領域
Field error in object 'event' on field 'endTime': rejected value
[12:00] codes
[typeMismatch.event.endTime,typeMismatch.endTime,typeMismatch.java.time.LocalTime,typeMismatch]
arguments
[org.springframework.context.support.DefaultMessageSourceResolvable:
codes [event.endTime,endTime] arguments [] default message [endTime]]
default message [Failed to convert property value of type
'java.lang.String' to required type 'java.time.LocalTime' for property
'endTime' nested exception is
org.springframework.core.convert.ConversionFailedException: Failed to
convert from type [java.lang.String] to type [java.time.LocalTime] for
value '12:00' nested exception is java.lang.IllegalArgumentException:
Parse attempt failed for value [12:00]]
序列化格式數據使用jQuery AJAX方法發佈。序列化的數據如下所示:
eventDate=27%2F01%2F2017&eventType=REN&maxParticipants=10&startTime=09%3A00&endTime=12%3A00
如何讓Spring正確解析序列化的時間字段?
我使用Java 8
爲我節省了很多時間。 Upvoting。請添加相關內容(書籍或教程)。謝謝,。 –
@Vito,感謝您的加入!我用來回答這個問題的唯一資源是已經在答案中鏈接的JavaDoc頁面。就更普遍的閱讀材料而言,我一直認爲公開的[Spring文檔](https://spring.io/docs)非常好。 –