我有两个用于外部API响应类:
A类:
@JsonIgnoreProperties(ignoreUnknown = true)
@Getter
@Setter
public class ClassA {
private SubClass subClass;
@Getter
@Setter
public static class SubClass {
Integer total;
Integer perPage;
List<Data> dataList;
@Getter
@Setter
public static class Data {
private String field1;
private String field2;
private int field3;
}
}
}
B类:
@JsonIgnoreProperties(ignoreUnknown = true)
@Getter
@Setter
public class ClassB {
private SubClass subClass;
@Getter
@Setter
public static class SubClass {
Integer total;
Integer perPage;
List<Data> dataList;
@Getter
@Setter
public static class Data {
private String field1;
private int field2;
private Date field3;
}
}
}
使用ObjectMapper进行反序列化:
ClassA classA =
mapper.readValue(bodyResponse, ClassA.class);
在使用继承并在以后使用反序列化时,消除这些类中重复代码的最佳方法是什么?
1条答案
按热度按时间z31licg01#
你需要使根和子类通用。使用
TypeReference
来提供你期望的数据类。看下面的例子:以上代码打印: