gpt4 book ai didi

java - @JsonSerialize 与泛型

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

我有以下代码将 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;

有什么帮助吗?

最佳答案

如果你使用 jackson 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;

关于java - @JsonSerialize 与泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16316818/

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