gpt4 book ai didi

java - Jackson 注释不适用于自定义日期序列化器

转载 作者:行者123 更新时间:2023-11-30 04:22:22 25 4
gpt4 key购买 nike

我读了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似乎只接受 boolean 值作为参数,而不是annotations doc其中指出:

@JsonValue(method): used to mark a method thats return value is to be used as serialization for the object; often used to mark String-producing methods (like toString()) to produce JSON primitive value serialization Blockquote

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

最佳答案

您应该使用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()));
}
}

关于java - Jackson 注释不适用于自定义日期序列化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16736918/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com