假设你有一个像这样的类:
public class GeneralResponseList<T> {
@JsonProperty("list")
private List<T> list;
// Getters and setters
}
您可以使用TypeReference<T>
:
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);