从包装类杰克逊那里得到确切的类 [英] Derive the exact class from the wrapping class Jackson

查看:113
本文介绍了从包装类杰克逊那里得到确切的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设我们有以下结构:

Lets assume that we have the following structure:

class BaseClass {
    ...
    String typeOfSomeClass;
    SomeClassBasedOnType someClassBasedOnType;
}

@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=As.PROPERTY, property="BaseClass.typeOfSomeClass")
@JsonSubTypes({
    @Type(value = SomeClassBasedOnTypeImpl1.class, name="type1"),
    @Type(value = SomeClassBasedOnTypeImpl2.class, name="type2")
})
interface SomeClassBasedOnType {
}
@JsonTypeName("type1")
class SomeClassBasedOnTypeImpl1 implements SomeClassBasedOnType {
    String str1;
}
@JsonTypeName("type2")
class SomeClassBasedOnTypeImpl2 implements SomeClassBasedOnType {
    String str2;
}

通过上述结构,我想使用Jackson存储JSON。我需要解析的两个可能的JSON是:

With the above structure I want to store a JSON using Jackson. The two possible JSONs that I need to parse are:

{"typeOfSomeClass":"type1", "someClassBasedOnType": {"str1":"someValue"}}

{"typeOfSomeClass":"type2", "someClassBasedOnType": {"str2":"someValue"}}

这是我用来反序列化JSON的代码:

Here is my code that I use to deserialize the JSON:

BaseClass baseClass = new ObjectMapper().readValue(someJsonAsString, BaseClass.class);

唯一的问题是我不知道如何从基础JSON中获取类型。语法: ... property =BaseClass.typeOfSomeClass仍然在SomeClassBasedOnType实现类中查找属性。任何想法如何指定我需要包装类中的属性?

The only thing is that I don't know how to get the type from the "base" JSON. The syntax: ...property="BaseClass.typeOfSomeClass" still looks for a property in the SomeClassBasedOnType implementing class. Any ideas how to specify that I need the property from the wrapping class ?

只是为了澄清基础JSON包含许多键,它们都是相同的,包括键someClassBasedOnType。然而,关键someClassBasedOnType可能包含两个不同的JSON对象(具有不同的键),并且区分这些对象的方式基于baseJSON中名为typeOfSomeClass的键的值。

Just to clarify the "base" JSON contains many keys, which are all the same including the key someClassBasedOnType. The key someClassBasedOnType however may contain two different JSON objects(with different keys) and the way to distinguish those objects is based on the value of the key in the "base" JSON called typeOfSomeClass.

推荐答案

以下是我的问题的解决方案,但 JsonTypeInfo.As.EXTERNAL_PROPERTY 自1.9版以来:(

Here is the solution for my problem, however the JsonTypeInfo.As.EXTERNAL_PROPERTY is since 1.9 version :(

Jackson JsonTypeInfo.As.EXTERNAL_PROPERTY无法按预期工作

这篇关于从包装类杰克逊那里得到确切的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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