Passing dates as JSON using Spring MVC and Jackson

I have a class with the java.util.Date field that I want to pass from the client to the Spring controller. The controller returns HTTP 415 whenever I make a request. I tried to add a custom serializer, as can be seen from many other questions that I managed to find. The custom serializer works because my controller, which retrieves the resource, retrieves them in a custom format, but the controller does not recognize JSON. If I completely delete the date, the controller works, so I know that the problem is with this field.

Ideally, I want to get them in the standard long representation, but I cannot force the controller to accept any format.

controller

@RequestMapping(method = RequestMethod.POST) @ResponseBody public ResponseEntity<String> addEvent(ModelMap model, @RequestBody Event event) { eventService.saveEvent(event); return new ResponseEntity<String>(HttpStatus.CREATED); } 

The class to be serialized (getters and setter are omitted, although I also tried annotation there.

 public class Event implements Serializable { private static final long serialVersionUID = -7231993649826586076L; private int eventID; private int eventTypeID; @JsonSerialize(using = DateSerializer.class) private Date date; 

Serializer

 private static final SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy"); @Override public void serialize(Date date, JsonGenerator gen, SerializerProvider provider) throws IOException, JsonProcessingException { String formattedDate = dateFormat.format(date); gen.writeString(formattedDate); } 

And the JSON received by my GET controller (I will be more accurate when I can get it to work at all)

 {"eventID":1,"eventTypeID":2,"date":"02-01-2014"} 
+2
source share
2 answers

You have a serializer but no deserializer, so it only works in one way ...

You will also need:

  @JsonDeserialize(using = DateDeserializer.class) 

(with DateDeserializer using the same date format).

Why there is no interface for both, this is a secret for me :-)

+4
source

Instead of a string, just pass the date object from jsp, as shown below.

 var date = new Date(); var formData = {'date':date}; 

And in dto make a variable like java.util.Date.

0
source

Source: https://habr.com/ru/post/1201740/


All Articles