我有以下代码将joda的LocalDate序列化为String:
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;
我想传递dateformat模式,例如(yyyy-MM-dd)在我宣布的时候上课。
我想用泛型这样的东西:
JodaDateSerializer<T>
T String;
但我不知道如何在我声明sendDate变量的地方使用它:
@JsonSerialize(using = JodaDateSerializer<???>.class)
LocalDate sentDate;
任何帮助?
答案 0 :(得分:2)
如果你使用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;