试图实现这个
@RequestMapping
public String helloWorld(@RequestBody Parent interface){
// do something with interface
}
其中Parent
是一个接口,而Child1
和Child2
是实现。
因为这些是第三方库.class文件,所以我无法使用@JsonTypeInfo
这种情况有解决办法吗?
答案 0 :(得分:1)
是的,您可以使用Jackson Mixin为第三方/不可接触的课程提供杰克逊注释。
https://github.com/FasterXML/jackson-docs/wiki/JacksonMixInAnnotations
这个例子相当陈旧,从这里开始提供,但从上次实现MixIn时看起来仍然正确,
http://programmerbruce.blogspot.co.uk/2011/05/deserialize-json-with-jackson-into.html
上面的例子5,
{ "animals":
[
{"type":"dog","name":"Spike","breed":"mutt",
"leash_color":"red"},
{"type":"cat","name":"Fluffy",
"favorite_toy":"spider ring"}
]
}
import java.io.File;
import java.util.Collection;
import org.codehaus.jackson.annotate.JsonSubTypes;
import org.codehaus.jackson.annotate.JsonTypeInfo;
import org.codehaus.jackson.annotate.JsonSubTypes.Type;
import org.codehaus.jackson.map.ObjectMapper;
public class Foo
{
public static void main(String[] args) throws Exception
{
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(
new CamelCaseNamingStrategy());
mapper.getDeserializationConfig().addMixInAnnotations(
Animal.class, PolymorphicAnimalMixIn.class);
mapper.getSerializationConfig().addMixInAnnotations(
Animal.class, PolymorphicAnimalMixIn.class);
Zoo zoo =
mapper.readValue(new File("input_5.json"), Zoo.class);
System.out.println(mapper.writeValueAsString(zoo));
}
}
class Zoo
{
public Collection<Animal> animals;
}
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "type")
@JsonSubTypes({
@Type(value = Cat.class, name = "cat"),
@Type(value = Dog.class, name = "dog") })
abstract class PolymorphicAnimalMixIn
{
}
abstract class Animal
{
public String name;
}
class Dog extends Animal
{
public String breed;
public String leashColor;
}
class Cat extends Animal
{
public String favoriteToy;
}
您可以使用Jackson2ObjectMapperBuilder
或Jackson2ObjectMapperFactoryBean
在Spring Boot中注册MixIn。
可以在此处找到上述Spring Boot世界中的上述工作示例,其中测试验证了Cat / Dog的成功POST,例如:父类的具体实现。