Jackson 基于类型反序列化 [英] Jackson deserialize based on type

查看:41
本文介绍了Jackson 基于类型反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下格式的 JSON:

Lets say I have JSON of the following format:

{
    "type" : "Foo"
    "data" : {
        "object" : {
            "id" : "1"
            "fizz" : "bizz"
            ...
        },
        "metadata" : {
            ...
        },
        "owner" : {
            "name" : "John"
            ...
        }
    }
}

我试图避免自定义反序列化器并尝试将上述 JSON(称为 Wrapper.java)反序列化为 Java POJO.类型"字段指示对象"反序列化,即.type = foo 表示使用 Foo.java 反序列化对象"字段.(如果 type = Bar,则使用 Bar.java 反序列化对象字段).元数据/所有者将始终使用一个简单的 Jackson 注释的 Java 类为每个对象反序列化相同的方式.有没有办法使用注释来实现这一点?如果没有,如何使用自定义解串器完成此操作?

I am trying to avoid custom deserializer and attempting to deserialize the above JSON (called Wrapper.java) into Java POJOs. The "type" field dictates the "object" deserialization ie. type = foo means the deserialize the "object" field using the Foo.java. (if type = Bar, use Bar.java to deserialize the object field). Metadata/owner will always deserialize the same way using a simple Jackson annotated Java class for each. Is there a way to accomplish this using annotations? If not, how can this be done using a custom deserializer?

推荐答案

仅注解方法

替代自定义反序列化器方法,您可以针对仅注释的解决方案使用以下方法(类似于Spunc 的答案 中描述,但使用 type 作为 外部属性):

Annotations-only approach

Alternatively to the custom deserializer approach, you can have the following for an annotations-only solution (similar to the one described in Spunc's answer, but using type as an external property):

public abstract class AbstractData {

    private Owner owner;

    private Metadata metadata;

    // Getters and setters
}

public static final class FooData extends AbstractData {

    private Foo object;

    // Getters and setters
}

public static final class BarData extends AbstractData {

    private Bar object;

    // Getters and setters
}

public class Wrapper {

    private String type;

    @JsonTypeInfo(use = Id.NAME, property = "type", include = As.EXTERNAL_PROPERTY)
    @JsonSubTypes(value = { 
            @JsonSubTypes.Type(value = FooData.class, name = "Foo"),
            @JsonSubTypes.Type(value = BarData.class, name = "Bar") 
    })
    private AbstractData data;

    // Getters and setters
}

在这种方法中,@JsonTypeInfo 设置为使用 type 作为 外部属性 以确定映射data 属性的正确类.

In this approach, @JsonTypeInfo is set to use type as an external property to determine the right class to map the data property.

JSON 文档可以反序列化如下:

The JSON document can be deserialized as following:

ObjectMapper mapper = new ObjectMapper();
Wrapper wrapper = mapper.readValue(json, Wrapper.class);  

这篇关于Jackson 基于类型反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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