Java:在运行时将Json对象解析为子类

Java:在运行时将Json对象解析为子类,java,json,Java,Json,我有下面的POJO @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(Include.NON_NULL) @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include =JsonTypeInfo.As.PROPERTY) @JsonSubTypes({ @JsonSubTypes.Type(value = Child1.class, name = "Child1"), @JsonSu

我有下面的POJO

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_NULL)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include =JsonTypeInfo.As.PROPERTY)
@JsonSubTypes({
   @JsonSubTypes.Type(value = Child1.class, name = "Child1"),
   @JsonSubTypes.Type(value = Child2.class, name = "Child2") 
})
class parent{
 string commonFeaure;
}
class child1 extends parent{
  String child1Feature;

}
class child2 extends parent{
  String child2Feature;
}
我在解析Json时遇到两个问题:

1-我的服务接受可能是child1或child2类型的json对象,如何在运行时进行映射,我在json处添加了“@type”,但我必须在映射处指定子类,如下所示,以将其映射到child1:

ObjectMapper mapper = new ObjectMapper();
Child1 c = mapper.readValue(jsonInput,Child1.class);
如何在不指定代码处的cast类的情况下使其动态化

2-如果一个类有一个对许多其他类来说都是超级类的对象,那么在对Json对象进行配对时,它会将其转换为超级类,而@type会指定一个子类

例如:

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_NULL)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include =JsonTypeInfo.As.PROPERTY)
@JsonSubTypes({
   @JsonSubTypes.Type(value = SubFeature .class, name = "SubFeature ")
})
class X {
  Feature x;
}
class Feature {
}
Class SubFeature extends Feature {
} 

在Json中,我添加了“@type”:“SubFeature”,但在将其解析为Java类时,它解析为Feature?如何解决此问题?

您可以在父类上使用以下注释:

    @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
    @JsonSubTypes({
            @Type(value = SubFeature.class, name = "SubFeature")
    })
    class Feature {
    }
然后

应返回正确的子类类型


您将在此处找到更多信息:

您可以在父类上使用以下注释:

    @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
    @JsonSubTypes({
            @Type(value = SubFeature.class, name = "SubFeature")
    })
    class Feature {
    }
然后

应返回正确的子类类型


您将在此处找到更多信息:

谢谢@arnaud,是的,我做了完全相同的操作,它将其解析为Feature而不是Subfeature可能是因为该类是json中的顶级类。尝试创建一个包含例如
列表
的包装类(比如
功能
),并序列化/反序列化此包装,而不是直接创建一个
功能
对象。谢谢@arnaud,是的,我做了完全相同的操作,它将其解析为功能而不是子功能可能是因为该类是json中的顶级类。尝试创建一个包含例如
列表
的包装类(比如
功能
),并序列化/反序列化此包装,而不是直接创建
功能
对象。