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

查看:29
本文介绍了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);


我知道 Jackson 可以在 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天全站免登陆