Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
806 views
in Technique[技术] by (71.8m points)

java - Passing a date as JSON with Spring MVC and Jackson

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 :-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...