如何使JsonGenerator打印日期和日期时间值? [英] How to make JsonGenerator pretty-print Date and DateTime values?

查看:376
本文介绍了如何使JsonGenerator打印日期和日期时间值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用这种方法将任何对象转换为json字符串:

I'm using this method to convert any object to a json string:

private String objectToJson(Object object) throws IOException {
        // write JSON
        StringWriter writer = new StringWriter();
        ObjectMapper mapper = new ObjectMapper();
        final JsonGenerator jsonGenerator = mapper.getJsonFactory().createJsonGenerator(writer);
        jsonGenerator.setPrettyPrinter(new DefaultPrettyPrinter());

        mapper.writeValue(jsonGenerator, object);
        return writer.toString();
    }

当打印的对象包含java.util.Date或jodatime的DateTime,打印值是自纪元以来的毫秒数。相反,我想以标准的HH:MM:SS表示法打印出来。

When the object being printed contains fields that are java.util.Date or jodatime's DateTime, the printed value is the number of milliseconds since the epoch. I would like, instead, to pretty-print them in a standard "HH:MM:SS" notation. How should I go about doing this?

推荐答案

因为历元时间戳(1970年1月1日以来的毫秒数)是最有效和准确地表达时间,几乎所有日期和时间相关的对象都被序列化。您当然可以覆盖它,如果您想使用问题中提到的格式,则需要在代码中添加以下内容:

Because the epoch timestamp (number of milliseconds since January 1st, 1970, UTC) is the most efficient and accurate representation of the time, nearly all date and time related objects are serialized to it. You can of course overwrite it and if you want to use the format mentioned in the question, you'd need to add the following to your code:

DateFormat myDateFormat = new SimpleDateFormat("hh:mm:ss");
objectMapper.getSerializationConfig().setDateFormat(myDateFormat);
objectMapper.getDeserializationConfig().setDateFormat(myDateFormat); 

有关Jackson JSON处理器中日期和时间的更多信息,请参阅以下链接: http://wiki.fasterxml.com/JacksonFAQDateHandling

For more information regarding dates and times in the Jackson JSON-processor see the following link: http://wiki.fasterxml.com/JacksonFAQDateHandling

这篇关于如何使JsonGenerator打印日期和日期时间值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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