小编典典

用Jackson和Spring序列化Joda DateTime

spring-boot

我在将Joda DateTime从Java序列化和反序列化并使用Spring Boot和Jackson-Jackson-databind
2.5.2重新序列化时遇到问题。我的pom.xml看起来像这样。

    <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.2</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-joda</artifactId>
    <version>2.5.2</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>1.2.1.RELEASE</version>
</dependency>

当我序列化DateTime对象时,我得到一个代表DateTime的整数。不是我实际期望的,但是很好。但是当我去保存我的对象时,出现以下错误…

Failed to convert property value of type 'java.lang.String' to required type 'org.joda.time.DateTime' for property 'endTime';
nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type org.joda.time.DateTime for value '1428600998511'

由于某种原因,它会将其序列化为整数,然后将其反序列化为好像是字符串,而不是字符串。我还尝试在调用其余服务之前设置endTime = new
Date(intValue),并且尝试将“ Tue Apr 28 2015 00:00:00
GMT-0700(PDT)”之类的字符串转换为DateTime也失败。

我究竟做错了什么?

更新:

这里是JSON,我得到 我立即尝试POST右后卫。

{
    id: 4,
    username: "",
    name: "eau",
    email: "aoue",
    verbatimLocation: null,
    latitude: null,
    longitude: null,
    startTime:null,
    endTime: 1429034332312,
    description: "ueoa",
    media: [ ],
    timeSubmitted: 1428600998000,
    status: null,
    submissionid: null
}

阅读 336

收藏
2020-05-30

共1个答案

小编典典

对于更可重用的机制,您可以创建一个JsonSerializer

/**
 * When passing JSON around, it's good to use a standard text representation of
 * the date, rather than the full details of a Joda DateTime object. Therefore,
 * this will serialize the value to the ISO-8601 standard:
 * <pre>yyyy-MM-dd'T'HH:mm:ss.SSSZ</pre>
 * This can then be parsed by a JavaScript library such as moment.js.
 */
public class JsonJodaDateTimeSerializer extends JsonSerializer<DateTime> {

    private static DateTimeFormatter formatter = ISODateTimeFormat.dateTime();

    @Override
    public void serialize(DateTime value, JsonGenerator gen, SerializerProvider arg2)
            throws IOException, JsonProcessingException {

        gen.writeString(formatter.print(value));
    }

}

然后,您可以使用以下get方法注释您的方法:

@JsonSerialize(using = JsonJodaDateTimeSerializer.class)

这使您可以在整个应用程序中使用一致的格式,而无需在各处重复文本模式。它也可以识别时区。

2020-05-30