简体   繁体   中英

Creating JSON from httprequest and then parsing it

In my controller I want to parse httprequest (JSON sent by me) to create new ToDoItem. I will shoot POST at localhost:8080/todos/new with JSON and my controller should turn that httprequest to JSON and then parse data from it and use it in the contructor. Here is my code so far:

// 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);
}

Btw what would be the best choice to use as Date here? Is Calendar ok? Talking about parsing and sending it in a JSON.

EDIT: My entity with annotations (setters and getters ommited):

@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;
}

And when I send:

{
"title":"testtodo",
"dueDate": [
    2017,
    10,
    06
]
}

I get Bad Request error:

{
"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"
}

This is how I would do it.

// 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);

Note that you will need a converter to convert the date in json to LocalDate in your ToDoItem object. Research MappingJackson2HttpMessageConverter for more info.

If you want to convert yourself, you can use a dto instead that has dueDate of type String and convert to LocalDate in java code and then convert the dto to your ToDoItem entity object.
public String newToDo(@RequestBody TodoItemDto todoItemDto)

I prefer java.time.LocalDate .

UPDATE
JSON deserializer can also be used here, checkout the following post:
jsong deserialization

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM