繁体   English   中英

Java:长格式的 util.Date 对象

[英]Java: util.Date object in long format

如何返回具有 long 值的 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": exception from

您可以将带有shape = Shape.NUMBER参数的@JsonFormat注释放在现有的 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}

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

return new Date(date.getTime());

您可以尝试像这样使用它:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM