在我的控制器中,我想解析httprequest(我发送的JSON)来创建新的ToDoItem。我将在localhost:8080 / todos / new用JSON拍摄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);
}
顺便说一句,在这里使用Date的最佳选择是什么?日历好吗?谈论解析并以JSON格式发送它。
编辑: 带有注释的实体(设置者和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"
}
答案 0 :(得分:1)
我就是这样做的。
// CREATE NEW TODOITEM FROM SENT JSON
@PostMapping("/todos/new")
public String newToDo(@RequestBody TodoItem todoItem) {
String title = todoItem.getTitle(); // extract title
LocalDate dueDate = todoItem.getDueDate; // extract dueDate
// getting logged in user
User currentUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
User userFromDb = userRepository.findOne(currentUser.getId());
ToDoItem newToDoItem = new ToDoItem(userFromDb, title, dueDate);
请注意,您需要一个转换器将json中的日期转换为LocalDate
对象中的ToDoItem
。研究MappingJackson2HttpMessageConverter
了解更多信息。
如果您想要转换自己,可以使用dto,而dueDate
类型为String
,并在java代码中转换为LocalDate
,然后将dto转换为{{ 1}}实体对象
ToDoItem
我更喜欢public String newToDo(@RequestBody TodoItemDto todoItemDto)
。
<强>更新强>
也可以在这里使用JSON解串器,查看以下帖子:
jsong deserialization