1

我阅读了杰克逊的注释文档,但我仍然找不到如何从注释中调用自定义序列化程序来序列化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似乎只接受一个布尔值作为参数,而不是注释文档,它声明:

@JsonValue(method):用于标记返回值将用作对象序列化的方法;常用于标记字符串生成方法(如 toString())以生成 JSON 原始值序列化 Blockquote

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

4

1 回答 1

2

您应该使用JsonSerialize注释。而你的 DateSerializer 实现包含错误。我认为,想要序列化日期值而不是名称 - 使用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()));
    }
}
于 2013-05-26T20:21:12.053 回答