简体   繁体   English

Jackson 将日期字符串反序列化为 Long

[英]Jackson deserialize date string to Long

Can Java Jackson deserialize a json string date into a Java Long field (milliseconds from epoch)? Can Java Jackson deserialize a json string date into a Java Long field (milliseconds from epoch)?

This is an example of json field to be deserialized:这是要反序列化的 json 字段的示例:

"timestamp": "2022-01-02T03:04:05Z",

and this is the same field in the Java class, with the current annotations:这是 Java class 中的相同字段,具有当前注释:

@JsonFormat(shape = JsonFormat.Shape.NUMBER, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX", timezone = "UTC")
@JsonProperty("timestamp") 
@JsonPropertyDescription("blah, blah\r\n")
public Long timestamp;

However, an exception happens:但是,会发生异常:

com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type java.lang.Long from String "2022-01-02T06:49:05Z": not a valid Long value com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type java.lang.Long from String "2022-01-02T06:49:05Z": not a valid Long value

Any hint?有什么提示吗? Thanks.谢谢。

The answer by Maurice is correct, it only suffers from using the notoriously troublesome and long outdated SimpleDateFormat and Date classes. Maurice 的回答是正确的,它只是受到使用臭名昭著的麻烦和长期过时的SimpleDateFormatDate类的影响。 Also the deserialize method is much simpler without them:没有它们, deserialize化方法也简单得多:

@Override
public Long deserialize(JsonParser jsonparser, DeserializationContext context)
        throws IOException, JsonProcessingException {
    String date = jsonparser.getText();
    return Instant.parse(date).toEpochMilli();
}

Use a custom date deserializer like this one:使用像这样的自定义日期反序列化器:

public class CustomDateDeserializer extends StdDeserializer<Long> {

    private SimpleDateFormat formatter = 
      new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");

    public CustomDateDeserializer() {
        this(null);
    }

    public CustomDateDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public Long deserialize(JsonParser jsonparser, DeserializationContext context)  
      throws IOException, JsonProcessingException {
        String date = jsonparser.getText();
        try {
            return formatter.parse(date).toInstant().toEpochMilli();
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
}

Next annotate your field with @JsonDeserialize(using = CustomDateDeserializer.class) .接下来使用@JsonDeserialize(using = CustomDateDeserializer.class)注释您的字段。

@JsonDeserialize(using = CustomDateDeserializer.class)
public Long timestamp;

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

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