Jackson注释不使用自定义日期序列化程序

时间:2013-05-24 14:07:38

标签: java serialization annotations jackson

我阅读了Jackson's annotations doc,但我仍然无法找到如何从注释中调用自定义序列化程序来序列化java.sql.Date对象。

class Test {
    java.sql.Date mDate = null;

    @JsonValue("serializeDate")       //@JsonValue(DateAsTimestampSerializer.class)
    public Date getCreationDate() {
        return mDate;
    }

    public void String serializeDate(Date d) {
        return String.valueOf(d.getTime());
    }

    class DateAsTimestampSerializer extends JsonSerializer<Date>
    {
         @Override
         public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) 
              throws IOException, JsonProcessingException {
             jgen.writeFieldName(String.valueOf(value.getTime()));
         }
    }
}

但注释@JsonValue似乎只接受一个布尔值作为参数,而不是annotations doc表示:

  

@JsonValue(方法):用于标记返回值的方法用作对象的序列化;通常用于标记String生成方法(如toString())以生成JSON原始值序列化   块引用

我使用正确的注释吗?我怎么能从Serializer而不是toString()返回值?

1 个答案:

答案 0 :(得分:2)

您应该使用JsonSerialize注释。你的DateSerializer实现包含bug。我想,想要序列化日期值而不是名称 - 使用writeString方法而不是writeFieldName方法。

参见我的例子:

import java.io.IOException;
import java.io.StringWriter;
import java.sql.Date;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

public class JacksonProgram {

    public static void main(String[] args) throws Exception {
        A a = new A();
        a.setDate(new Date(System.currentTimeMillis()));

        ObjectMapper objectMapper = new ObjectMapper();
        StringWriter writer = new StringWriter();
        objectMapper.writeValue(writer, a);
        System.out.println(writer);
    }
}

class A {

    @JsonSerialize(using = DateAsTimestampSerializer.class)
    private Date date;

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }
}

class DateAsTimestampSerializer extends JsonSerializer<Date> {
    @Override
    public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider)
            throws IOException, JsonProcessingException {
        jgen.writeString(String.valueOf(value.getTime()));
    }
}