【问题标题】:Json Deserialize Date not working [duplicate]Json反序列化日期不起作用[重复]
【发布时间】:2016-03-30 19:48:44
【问题描述】:

在 Json 列表中,我得到这样一个日期:“lastModifiedDate”:1459202400000”。序列化和反序列化类似乎没问题。

实体类:

import org.codehaus.jackson.map.annotate.JsonDeserialize;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.hibernate.validator.constraints.Email;
@Data
@ToString
@Entity
public class UserEntity implements Serializable {

    @JsonSerialize(using=JsonDateSerializer.class)
    @JsonDeserialize(using=JsonDateDeserializer.class)
    @Column(name = "LastModifiedDate", columnDefinition="DATETIME", nullable = true, insertable = true, updatable = true)
    private java.util.Date lastModifiedDate;

}

反序列化器类:

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.springframework.stereotype.Component;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.*;

@Component
public class JsonDateDeserializer extends JsonDeserializer<Date> {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        try {
            return dateFormat.parse(jsonParser.getText());
        } catch (Exception e) {
            throw new JsonParseException("Could not parse date", jsonParser.getCurrentLocation(), e);
        }
    }

怎么了? }

【问题讨论】:

  • 看起来您的 dateFormat 不是您的数据的格式。
  • 为什么会被标记为重复?在另一个问题中,没有关于 JSON 的内容。

标签: java json date


【解决方案1】:

您没有正确解析日期。现在您会收到一个以毫秒为单位的日期,因此您必须在格式化之前先创建一个日期,即:

dateFormat.format(new Date(Long.parseLong(jsonParser.getText())));

或者,如果您只想从中创建 Date 对象,只需跳过格式部分。

【讨论】:

  • 感谢您的回复。我也试过了,还是不行。我在控制台中添加了记录器,但在控制台上没有任何日志。我将反序列化更改为@JsonFormat,现在可以使用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-30
  • 2023-04-06
  • 2012-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-01
相关资源
最近更新 更多