[英]How can I deserialize a Json String to get polymorphic result using Java and Jackson Library?
I've a class CONTAINER, that contains a List . 我有一个CONTAINER类,其中包含一个List 。 BaseClass is not an abstract class, but there is 2 subtypes of BaseClass : BaseClassA and BaseClassB which each have extra fields.
BaseClass不是抽象类,但是BaseClass有2 个子类型: BaseClassA和BaseClassB ,每个子类型都有额外的字段。
BaseClass has an attribut enum Type, from which i can determinate if an object is BaseClass, BaseClassA or BaseClassB and that i want to use as a discriminator. BaseClass具有一个属性枚举类型,我可以从中确定对象是BaseClass,BaseClassA还是BaseClassB,并且希望将其用作区分符。
How can i tell Jackson the discriminator so when it deserialize the json string, it builds the correct object. 我怎样才能告诉Jackson鉴别器,所以当它反序列化json字符串时,它将建立正确的对象。 At the moment every object is instancied as a BaseClass so i cannot cast it in my java code.
目前,每个对象都被实例化为BaseClass,因此我无法将其强制转换为Java代码。 The same way as @DiscriminatorFormula & @DiscriminatorValue work for hibernate and entities
与@DiscriminatorFormula和@DiscriminatorValue用于休眠和实体的方式相同
I've found this question : How can I polymorphic deserialization Json String using Java and Jackson Library? 我发现了这个问题: 如何使用Java和Jackson库对Json String进行多态反序列化? which is kinda close but here the user only wants the basic type.
这有点接近,但是用户在这里只需要基本类型。
Guessing you have probably solved this but if not check out JsonTypeInfo as a way to annotate classes with subtypes for desrialization. 猜测您可能已经解决了这个问题,但如果没有解决,请签出JsonTypeInfo作为用子类型注释类以进行反序列化的方法。 This link http://programmerbruce.blogspot.com/2011/05/deserialize-json-with-jackson-into.html has a good explanation that is still valid.
此链接http://programmerbruce.blogspot.com/2011/05/deserialize-json-with-jackson-into.html具有很好的解释,仍然有效。 If you can't annotate your classes you can use configuration to set up mix-ins (see https://github.com/FasterXML/jackson-docs/wiki/JacksonMixInAnnotations ) that allow you to add annotations to existing classes.
如果您不能注释您的类,则可以使用配置来设置混合项(请参阅https://github.com/FasterXML/jackson-docs/wiki/JacksonMixInAnnotations ),该混合项可以为现有类添加注释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.