嵌套子类Child,反序列化后,不是Child,而是Parent,需要怎么处理呢
public class JsonTest {
@test public void test() {
Shell shell = new Shell(new Child(13).setName("zs"));
String json = JSON.toJSONString(shell);
log.info("json: {}", json); // 输出 {"parent":{"age":13,"name":"zs"}}
Shell after = JSON.parseObject(json, Shell.class);
log.info("after json: {}", JSON.toJSONString(after, SerializerFeature.WriteClassName)); // 这里输出,缺少子类age字段,因为示例化成了父类Parent
}
}
@DaTa@AllArgsConstructor@NoArgsConstructor
classShell{ // 壳
private Parent parent;
}
classParent{ // 父类
@getter private String name;
public Parent setName(String name) {
this.name = name;
return this;
}
}
@DaTa@EqualsAndHashCode(callSuper = false)@AllArgsConstructor@NoArgsConstructor
classChildextendsParent{ // 子类
private Integer age;
}
2条答案
按热度按时间nvbavucw1#
这样写不起作用
Shell after = JSON.parseObject(json, Shell.class, (FieldTypeResolver) (object, fieldName) -> {
if (fieldName.equals("parent")) {
return Child.class;
}
return null;
});
uurity8g2#
输出