JodaTime的序列化和反序列化日期为json

时间:2015-02-25 12:27:32

标签: java json jackson jodatime jackson-modules

根据此处的文档https://github.com/FasterXML/jackson-datatype-joda

以下代码段应传递

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());

final String INPUT_JSON = "{\"start\" : \"1972-12-28T12:00:01.000Z\"}";
Bean bean = mapper.readValue(INPUT_JSON, Bean.class);
String json = mapper.writeValueAsString(bean);
Assert.assertEquals(INPUT_JSON, json);

但是,这会返回:

org.junit.ComparisonFailure: 
Expected :{"start" : "1972-12-28T12:00:01.000Z"}
Actual   :{"start":94392001000}

这是我正在使用的pom文件:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>test</groupId>
    <artifactId>test</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.7</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-joda</artifactId>
            <version>2.4.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

</project>

为什么日期时间对象没有正确序列化?

1 个答案:

答案 0 :(得分:1)

测试似乎缺少此功能。

mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS ,false);