com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "field" (class



我有一个反序列化问题:试图转换继承父类的类。下面是我的班级

public class Base {
Parent parent;
public Parent getParent() {
return parent;
}
public void setParent(Parent parent) {
this.parent = parent;
}
}
-----------------
public class Parent {
String name;
String city;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
-----------------
public class Child extends Parent {
String field;
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
}

主要方法:

public class TestDeserial {
public static void main(String[] args) {
Child c = new Child();
c.setName("test1");
c.setCity("Mumbai");
c.setField("allow");
Base b = new Base();
b.setParent(c);
// Convert object to json
File file = new File("C:\temp\c.json");
try {
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(file, b);
} catch (IOException e) {
e.printStackTrace();
}

// Convert json to object
Base baseResult = null;
try (InputStream in = new FileInputStream("C:\temp\c.json")) {
ObjectMapper objMapper = new ObjectMapper();
baseResult = objMapper.readValue(in, Base.class);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}

错误:unrecognizedpropertyexception: Unrecognized field" field"(类com.mapper.example.Parent),未标记为可忽略(2个已知属性:& name", "city"])at[来源:(FileInputStream);line: 1, column: 52](通过引用链:com.mapper.example.Base["parent"]- " com.mapper.example.Parent["field"])

我不想在类文件中添加任何注释。

您需要告诉Jackson使用基于演绎的推理来确定适当的子类。Jackson将检查JSON中的字段,并与子类中的字段进行比较。

如果你不想在原始类中添加注释,那么你可以使用mix-in,例如:

@JsonTypeInfo(use = JsonTypeInfo.Id.DEDUCTION)
@JsonSubTypes({ @JsonSubTypes.Type(Child.class) })
public abstract class ParentMixin {}

,然后将其注册到ObjectMapper(用于反序列化):

ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(Parent.class, ParentMixin.class);

相关内容

最新更新