Reputation: 325
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"}
Upvotes: 2
Views: 22547
Reputation: 1539
Instead of string, just pass date object from jsp as below.
var date = new Date();
var formData = {'date':date};
And in the dto, make variable of type java.util.Date.
Upvotes: 0
Reputation: 7048
You have a serializer, but no deserializer, so it's only working one way...
You also need:
@JsonDeserialize(using = DateDeserializer.class)
(with a DateDeserializer using the same date format).
Why there isn't a single interface for both is a mystery to me :-)
Upvotes: 4