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"}
source share