使用现有的同级属性值对属性进行Jackson多态反序列化

使用现有的同级属性值对属性进行Jackson多态反序列化

本文介绍了使用现有的同级属性值对属性进行Jackson多态反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用了无法控制的Request/Response协议.

I have an existing Request/Response protocol using JSON that I have no control over.

示例1:响应JSON不需要任何多态反序列化

Example 1: response JSON not requiring any polymorphic deserialisation

{
  "name" : "simple_response"
  "params" : {
    "success" : true
  }
}

示例2:响应JSON需要对params属性进行多态反序列化

Example 2: response JSON requiring polymorphic deserialisation of params property

{
  "name" : "settings_response",
  "params" : {
    "success" : true,
    "settings" : "Some settings info"
  }
}

我的班级结构如下:

class Response { // Not abstract. Used if no specialized response properties needed
  @JsonProperty("params")
    @JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
            include = JsonTypeInfo.As.EXTERNAL_PROPERTY,
            property = "name")
    @JsonSubTypes({
            @JsonSubTypes.Type(value=GetSettingsResponseParams.class, name="settings_response")
    })
  Params params;
  String name; // Need to use its value to determine type of params
}

class Params {
  boolean success;
}

class GetSettingsResponseParams extends Params {
  String settings;
}

当我尝试对示例2"中的JSON进行反序列化时,我得到:

When I try to deserialise the JSON in "Example 2" I get:

Unexpected token (END_OBJECT), expected VALUE_STRING: need JSON String that contains type id (for subtype of com.foo.Params)

我在做什么错,我该如何解决?

What am I doing wrong and how can I fix it?

推荐答案

Response模型应类似于:

class Response {

    @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, property = "name", visible = true)
    @JsonSubTypes({
            @JsonSubTypes.Type(value = GetSettingsResponseParams.class, name = "settings_response"),
            @JsonSubTypes.Type(value = Params.class, name = "simple_response")
    })
    private Params params;
    private String name;

    // getters, settets, toString, etc.
}

上面的模型对于两个呈现的JSON有效载荷均正常工作.

Above model works properly for two presented JSON payloads.

这篇关于使用现有的同级属性值对属性进行Jackson多态反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 13:38