【问题标题】:Creating JSON from httprequest and then parsing it从 httprequest 创建 JSON 然后解析它
【发布时间】: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

标签: java json spring rest


【解决方案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 对象中的 LocalDate。研究MappingJackson2HttpMessageConverter 了解更多信息。

如果您想转换自己,您可以使用具有String 类型的dueDate 的dto,并在java 代码中转换为LocalDate,然后将dto 转换为您的ToDoItem 实体对象。
public String newToDo(@RequestBody TodoItemDto todoItemDto)

我更喜欢java.time.LocalDate

更新
JSON反序列化器也可以在这里使用,查看以下帖子:
jsong deserialization

【讨论】:

  • 但是如果我在 JSON 中对 LocalDate 使用标准格式,我还需要使用 MessageConverter 吗?或者你上面的代码工作得很好?
  • 是的,你需要。我有一段时间没试过了。我很确定这是我上次使用它的情况。您也可以为此使用 JSON 反序列化器。我已更新我的答案以包含此内容。
  • 你能告诉我如何使用它吗?我应该在我的实体中添加注释吗?将我的实体添加到我的帖子中。我还更新了我的控制器并解决了我遇到的错误
  • 1.确保添加最新的“jackson-datatype-jsr310”依赖项。 2.错误信息显示不允许使用前导零,请务必将您的json中的06更改为6。
猜你喜欢
  • 2022-09-23
  • 2015-05-11
  • 2023-03-05
  • 2014-03-08
  • 2017-03-24
  • 2021-02-02
  • 1970-01-01
  • 2021-03-28
  • 2019-10-23
相关资源
最近更新 更多