用Spring MVC和Jackson传递JSON的日期 [英] Passing a date as JSON with Spring MVC and Jackson

查看:355
本文介绍了用Spring MVC和Jackson传递JSON的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有java.util.Date字段的类,我希望从客户端传递给Spring控制器。每当我发出请求时,控制器都返回HTTP 415。我已经尝试添加自定义序列化程序,正如我能够找到的许多其他问题中所见。自定义序列化程序的工作原理是,我的控制器检索资源以自定义格式检索它们,但控制器不会确认JSON。如果我完全删除日期,控制器工作,所以我知道问题是在该字段。

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.

控制器

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

要序列化的类(省略了getter和setter,尽管我也试过了注释那里。

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;

序列化程序

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);
}

我的GET控制器检索到的JSON(我会更多确切地说,当我可以让它工作时)

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


推荐答案

你有一个序列化器,但没有解串器,所以它只能单向工作...

You have a serializer, but no deserializer, so it's only working one way...

你还需要:

 @JsonDeserialize(using = DateDeserializer.class)

(带有DateDeserializer使用相同的日期格式)。

(with a DateDeserializer using the same date format).

为什么两者都没有单一界面对我来说是个谜: - )

Why there isn't a single interface for both is a mystery to me :-)

这篇关于用Spring MVC和Jackson传递JSON的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆