Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
735 views
in Technique[技术] by (71.8m points)

java - how to make child class deserialize without type property in Jackson while type specified in parent class

I have a service that receives my parent interface as input in order to receive different types as input. interface is defined as below:

@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY)
@JsonSubTypes({
    @JsonSubTypes.Type(value = Person.class, name = "person"),
    @JsonSubTypes.Type(value = Employee.class , name = "employee")
})
public interface TestInterface {
}

and i have a service that gets TestInterface as below:

@RequestMapping(value="/convert", method = RequestMethod.POST)
@ResponseBody
public Person test(@RequestBody TestInterface object){}

this service must get json like below and works just file with type property:

 {"@type":"person","name":null,"family":"fami"}

the problem is when i have a service that receives the child class directly and i don't want to specify type property.

@RequestMapping(value="/convertPerson", method = RequestMethod.POST)
@ResponseBody
public Person test(@RequestBody Person object){}

in this example when i don't send type property i get (missing type id property) exception. is there any way to make it work without type id? i already tried the below config but it didn't solve the problem:

spring.jackson.deserialization.fail-on-missing-external-type-id-property=false

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

solved the problem by putting @JsonTypeInfo(use = JsonTypeInfo.Id.NONE) on top of child class. with this annotation child class can work independently without type and also parent interface will work fine with types.

@JsonTypeInfo(use = JsonTypeInfo.Id.NONE)
public class Person implements TestInterface{
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...