1

我有以下代码将 joda 的 LocalDate 序列化为字符串:

public class JodaDateSerializer extends JsonSerializer<ReadablePartial> {
    private static final String dateFormat = ("yyyy-MM-dd");
    @Override
    public void serialize(ReadablePartial date, JsonGenerator gen, SerializerProvider provider)
            throws IOException, JsonProcessingException {

        String formattedDate = DateTimeFormat.forPattern(dateFormat).print(date);

        gen.writeString(formattedDate);
    }
}

我像这样使用它:

@JsonSerialize(using = JodaDateSerializer.class)
LocalDate sentDate;

当我声明它时,我想将日期格式模式(例如(yyyy-MM-dd))传递给类。

我想使用这样的泛型:

JodaDateSerializer<T>

T String;

但我不确定如何在声明 sendDate 变量的地方使用它:

@JsonSerialize(using = JodaDateSerializer<???>.class)
LocalDate sentDate;

有什么帮助吗?

4

1 回答 1

2

如果您使用杰克逊 json 解析器。您不能将附加参数传递给 JsonSerialize 注释,也不能将泛型参数传递给 JsonSerializer 类。

我认为唯一的方法是为每个日期格式创建一个新的 JsonSerializer 子类,如下所示:

public abstract class JodaDateSerializer extends JsonSerializer<ReadablePartial> {

    protected abstract String getDateFormat();

    @Override
    public void serialize(ReadablePartial date, JsonGenerator gen, SerializerProvider provider)
            throws IOException, JsonProcessingException {

        String formattedDate = DateTimeFormat.forPattern(getDateFormat()).print(date);

        gen.writeString(formattedDate);
    }
}

public class LocalDateSerializer extends JodaDateSerializer {

    protected String getDateFormat(){
        return "yyyy-MM-dd";
    }

}

public class OtherDateSerializer extends JodaDateSerializer {

    protected String getDateFormat(){
        return "yyyy/MM/dd";
    }

}

然后为您的字段使用roper DateSerializer 类。

@JsonSerialize(using = LocalDateSerializer.class)
LocalDate sentDate;

@JsonSerialize(using = OtherDateSerializer.class)
OtherDate otherDate;
于 2013-05-01T11:37:49.300 回答