我对多态有一些问题(是多态的吗?)和杰克逊进行反序列化。
假设我有以下JSON结构
{
"list": [
"02/01/2018",
"03/01/2018",
"04/01/2018",
"05/01/2018",
"08/01/2018",
"05/02/2018"
]
}其中list可能包含不同类型的数据。我使用泛型用下面的POJO对数据结构进行建模。
public class GeneralResponseList<T> extends BaseResponse {
@JsonProperty("list")
private List<T> list;
@JsonProperty("paging")
private Paging paging;
@JsonProperty("sorting")
private List<Sorting> sorting;
// [CUT]
}如何为T类型指定反序列化器?我看过多态反序列化,但我认为它不能解决我的问题。
我还可以创建一个特定的LocalDateResponseList,它扩展了GeneralResponseList<LocalDate>。如何为特定响应指定反序列化器?
你能给我一个解决这个问题的办法或提示吗?
发布于 2018-07-05 10:25:21
假设您有一个类,如:
public class GeneralResponseList<T> {
@JsonProperty("list")
private List<T> list;
// Getters and setters
}您可以使用TypeReference
GeneralResponseList<LocalDate> response =
mapper.readValue(json, new TypeReference<GeneralResponseList<LocalDate>>() {});如果您有多个日期格式(正如您在注释中提到的那样),您可以编写一个自定义反序列化器来处理这个问题:
public class LocalDateDeserializer extends StdDeserializer<LocalDate> {
private List<DateTimeFormatter> availableFormatters = new ArrayList<>();
protected LocalDateDeserializer() {
super(LocalDate.class);
availableFormatters.add(DateTimeFormatter.ofPattern("dd/MM/yyyy"));
availableFormatters.add(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
}
@Override
public LocalDate deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException {
String value = p.getText();
if (value == null) {
return null;
}
for (DateTimeFormatter formatter : availableFormatters) {
try {
return LocalDate.parse(value, formatter);
} catch (DateTimeParseException e) {
// Safe to ignore
}
}
throw ctxt.weirdStringException(value, LocalDate.class, "Unknown date format");
}
}然后将反序列化器添加到模块中,并在Module实例中注册ObjectMapper:
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(LocalDate.class, new LocalDateDeserializer());
mapper.registerModule(module);https://stackoverflow.com/questions/51188665
复制相似问题