Jacking在没有@JsonSerialize的情况下将TimeStamp序列化为JSON?

时间:2016-05-19 00:31:12

标签: java json spring serialization jackson

我目前将日期存储为DateTime类型,但问题是当我进行API调用时,我在POJO中返回TimeStamp。由于Jackson自动将其转换为毫秒,我想将这些毫秒转换为Date,因此它更易于阅读。我们在工作中使用RedShift遇到了一些问题,试图使用JsonSerialize序列化日期,因为serialize似乎调用了错误的serialize方法来序列化JSON,导致在尝试存储时出现一些错误我们的数据进入Postgres SQL。有没有办法避免使用JsonSerialize序列化TimeStampDate?以下是JsonSerialize

的尝试

HibernateBaseClass.java

@JsonSerialize(using = CustomDateSerializer.class)
@Basic(optional=false)
@Column(name="created_on")
private Timestamp createdOn;

CustomDateSerializer.java

public class CustomDateSerializer extends JsonSerializer<Timestamp> {

    private static UserSession userSession = SessionManager.getUserSession();
    public static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
    public static final Locale userLocale = new Locale(userSession.getLocale().toString());
    public static final TimeZone userTimeZone = userSession.getTimeZone();

    @Override
    public void serialize(Timestamp timeStamp, JsonGenerator generator, SerializerProvider provider)
        throws IOException, JsonProcessingException {

        if (timeStamp == null) {
            generator.writeNull();
        } else {
            format.setTimeZone(userTimeZone);
            generator.writeString(format.format(timeStamp.getTime()));
        }
    }
    @Override
    public Class<Timestamp> handledType() {
        return Timestamp.class;
    }


    @Override
    public void serializeWithType(Timestamp value, JsonGenerator gen,
                              SerializerProvider serializers, TypeSerializer typeSer)
        throws IOException {
        serialize(value, gen, serializers);
    }
}

任何帮助将不胜感激,谢谢!

0 个答案:

没有答案