Java:长格式的util.Date对象

时间:2014-07-21 14:14:59

标签: java jackson

如何返回长值的Date对象? 类似的东西:

@JsonProperty("time")
    public Date getTimeInLong() {
       Date date = super.getTime();
       return date.getTime() //I want this value as date object
    }

原因是我试图将JSON属性time覆盖为长格式。但如果我将getter签名更改为public long getTime(){},我会从

中获得Conflicting getter definitions for property "time":异常

3 个答案:

答案 0 :(得分:2)

您可以将@JsonFormat注释与shape = Shape.NUMBER参数放在现有的getter方法上。这是一个例子:

public class JacksonJsonFormat {
    public static class Bean {
        @JsonFormat(shape = JsonFormat.Shape.NUMBER)
        public Date getTime() {
            return new Date();
        }
    }

    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.writeValueAsString(new Bean()));
    }
}

输出:

{"time":1406068019124}

答案 1 :(得分:1)

除非我误解你的问题,否则你可以这样做:

return new Date(date.getTime());

答案 2 :(得分:1)

您可以尝试使用它:

@JsonProperty("time")
    public Date getTimeInLong() {
       Date date = super.getTime();
       return  new Date (date.getTime());
    }