Jackson JSON库:如何实例化包含抽象字段的类 [英] Jackson JSON library: how to instantiate a class that contains abstract fields

查看:533
本文介绍了Jackson JSON库:如何实例化包含抽象字段的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将JSON字符串转换为java对象,但此对象的类包含抽象字段,Jackson无法实例化,也不会生成对象。告诉它关于抽象类的一些默认实现的最简单方法是什么,比如

I want to convert a JSON string into java object, but the class of this object contains abstract fields, which Jackson can't instantiate, and doesn't produce the object. What is the easiest way to tell it about some default implementation of an abstract class, like

setDefault(AbstractAnimal.class, Cat.class);

或根据JSON属性名称决定实现类,例如。对于JSON对象:

or to decide about the implementation class based on JSON attribute name, eg. for JSON object:

{
    ...
    cat: {...}
    ...
}

我愿意:

setImpl("cat", Cat.class);



我知道杰克逊可以在JSON中嵌入类信息,但是我不想使我使用的JSON格式复杂化。我想通过设置默认实现类或属性名称('cat')来决定使用哪个类 - 就像在XStream库中一样,你写的地方:


I know it's possible in Jackson to embed class information inside JSON, but I don't want to complicate the JSON format I use. I want to decide what class to use just by setting default implementation class, or by the attribute name ('cat') - like in XStream library, where you write:

xStream.alias("cat", Cat.class);

有没有办法这样做,特别是在一行中,还是需要更多代码?

Is there a way to do so, especially in one line, or does it require some more code?

推荐答案

有多种方式;在版本1.8之前,最简单的方法可能是:

There are multiple ways; before version 1.8, simplest way is probably to do:

@JsonDeserialize(as=Cat.class)
public abstract class AbstractAnimal { ... }

根据属性决定,最好使用 @JsonTypeInfo ,它自动嵌入(写入时)和使用类型信息。

as to deciding based on attribute, that is best done using @JsonTypeInfo, which does automatic embeddeding (when writing) and use of type information.

有多种类型的信息(类名,逻辑类型名称),以及包含机制(as-included-property,as-wrapper-array,as-wrapper-object)。此页面: https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization 解释了一些概念。

There are multiple kinds of type info (class name, logical type name), as well as inclusion mechanisms (as-included-property, as-wrapper-array, as-wrapper-object). This page: https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization explains some of the concepts.

这篇关于Jackson JSON库:如何实例化包含抽象字段的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆