【发布时间】:2017-06-16 07:36:10
【问题描述】:
在我的控制器中,我想解析 httprequest(我发送的 JSON)来创建新的 ToDoItem。我将使用 JSON 在 localhost:8080/todos/new 上拍摄 POST,我的控制器应该将该 httprequest 转换为 JSON,然后从中解析数据并在构造函数中使用它。 到目前为止,这是我的代码:
// CREATE NEW TODOITEM FROM SENT JSON
@PostMapping("/todos/new")
public ResponseEntity<ToDoItem> newToDo(
@RequestBody ToDoItem toDoItem,
Principal principal
) {
User currentUser = userRepository.findByUsername(principal.getName());
toDoItemService.addToDo(toDoItem, currentUser);
return ResponseEntity.ok(toDoItem);
}
顺便说一句,在这里用作日期的最佳选择是什么?日历好吗?谈论解析并以 JSON 格式发送。
编辑: 我的带有注释的实体(省略了 setter 和 getter):
@Entity
@Table (name = "TO_DO_ITEMS")
public class ToDoItem extends BaseEntity {
@Column(name = "TITLE", nullable = false)
private String title;
@Column(name = "COMPLETED")
private boolean completed;
@Column(name = "DUE_DATE", nullable = false)
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
protected LocalDate dueDate;
// a ToDoItem is only associated with one user
@ManyToOne(cascade=CascadeType.PERSIST)
@JoinColumn(name = "USER_ID")
private User user;
// JPA demands empty constructor
public ToDoItem() {}
public ToDoItem(User user, String title, LocalDate dueDate) {
this.user = user;
this.title = title;
this.dueDate = dueDate;
}
当我发送时:
{
"title":"testtodo",
"dueDate": [
2017,
10,
06
]
}
我收到错误请求错误:
{
"timestamp": 1485948636705,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.http.converter.HttpMessageNotReadableException",
"message": "Could not read document: Invalid numeric value: Leading zeroes not allowed\n at [Source: java.io.PushbackInputStream@4f15b887; line: 6, column: 4]\n at [Source: java.io.PushbackInputStream@4f15b887; line: 6, column: 3] (through reference chain: com.doublemc.domain.ToDoItem[\"dueDate\"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Invalid numeric value: Leading zeroes not allowed\n at [Source: java.io.PushbackInputStream@4f15b887; line: 6, column: 4]\n at [Source: java.io.PushbackInputStream@4f15b887; line: 6, column: 3] (through reference chain: com.doublemc.domain.ToDoItem[\"dueDate\"])",
"path": "/todos/new"
}
【问题讨论】:
-
您可以使用此网站通过粘贴您的 json 样本来使用 Java 创建模型:jsonschema2pojo.org