I have a class with a java.util.Date field that I wish to pass from a client to a Spring controller. The controller returns HTTP 415 whenever I make the request. I have tried adding a custom serializer as seen in many other questions I've been able to find. The custom serializer works, in that my controller which retrieves resource retrieves them in the custom format but the controller will not acknowledge the JSON. If I remove the date entirely, the controller works so I know the issue is with that field.
Ideally, I want to receive them in the default long representation, but I can't get the controller to accept either 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 omitted, though I also tried the 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 retrieved by my GET controller (I'll be more precise when I can get it working at all)
{"eventID":1,"eventTypeID":2,"date":"02-01-2014"}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…