Java 杰克逊日期格式与@JsonFormat?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24142892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hymanson date format with @JsonFormat?
提问by ligboo
I want to serialize certain Calendar fields of a POJO with a specific format.
我想用特定格式序列化 POJO 的某些日历字段。
with no annotations, fields like this:
没有注释,字段如下:
private Calendar timestamp1;
private Calendar timestamp2;
produce JSON like this:
像这样生成 JSON:
{ ..., timestamp1: 1402402106000, timestamp2: 1402488595000, ... }
I would to add a field formatted as a string as it actually represents a Day as a 24-hour unit, not a specific instant of time. But when I add a new field with an annotation:
我会添加一个格式化为字符串的字段,因为它实际上将一天表示为 24 小时单位,而不是特定的时间。但是当我添加一个带有注释的新字段时:
@JsonFormat(pattern = "yyyy-MM-dd")
private Calendar oneDay;
I was hoping to get JSON like this:
我希望得到这样的 JSON:
{ ..., timestamp1: 1402402106000, timestamp2: 1402488595000, oneDay: "2014-06-12", ... }
Instead, I got a the following exception:
相反,我得到了以下异常:
com.fasterxml.Hymanson.databind.JsonMappingException:
Cannot format given Object as a Date
(through reference chain: java.util.HashMap["data"]->java.util.ArrayList[0]-myPojo["oneDay"])
What am I doing wrong?
我究竟做错了什么?
I'm using Hymanson 2.2.0
我正在使用Hyman逊 2.2.0
回答by Jonathan Larson
Here's what I've used: @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
这是我用过的: @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
That works for me.
这对我行得通。