作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下代码将 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/
我是一名优秀的程序员,十分优秀!