Jackson多态反序列化:JsonMappingException

问题描述 投票:0回答:2

我想我有一个父类 Parameter ,它有 2 个子类 ComboParameterIntegerParameter

@JsonSubTypes({
    @JsonSubTypes.Type(value = IntegerParameter.class, name = "integerParam"),
    @JsonSubTypes.Type(value = ComboParameter.class, name = "comboParam")
})
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = As.WRAPPER_OBJECT)
 public abstract class Parameter {
String regEx;
}


@JsonTypeName("integerParam")
public class IntegerParameter extends Parameter {
}

@JsonTypeName("comboParam")
public class ComboParameter extends Parameter {
List<String> values;
}

我有一个具有属性参数的类

class A {
@JsonUnwrapped
Parameter parameter;
}

对象的序列化

A
抛出异常

com.fasterxml.jackson.databind.JsonMappingException:展开的属性需要使用类型信息:如果不禁用则无法序列化

SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS

如果我删除注释

@JsonUnwrapped
我将得到一个像那样的json

{
     parameter:{
          integerParam:{
               regEx: regExVal
          }
     }
}

我需要的是这样的json:

{
     integerParam:{
           regEx: regExVal
     }
}

NB 我正在使用 Jackson 2.4.4

json spring-mvc serialization jackson deserialization
2个回答
3
投票

不认为这个问题有简单干净的解决方案。但这里有一些如何解决这个问题的想法(Gist demo适用于这两种情况):

选项 1: 在属性上方添加

@JsonIgnore
,并在顶级 bean 中添加
@JsonAnyGetter
。易于实现,但在 bean 中拥有静态 ObjectMapper 并不好,并且必须将此代码复制到具有 Parameter 属性的每个 ben

public class A {

    @JsonIgnore
    Parameter parameter;

    // can put ObjectMapper and most of this code in util class
    // and just use JacksonUtils.toMap(parameter) as return of JsonAnyGetter

    private static ObjectMapper mapper = new ObjectMapper();

    /************************ Serialization ************************/

    @JsonAnyGetter
    private Map<String, Object> parameterAsMap(){
        return mapper.convertValue(parameter, Map.class); 
    }

    /************************ Deserialization **********************/

    @JsonAnySetter
    private void parameterFromMap(String key, JsonNode value)  {
        try {
            parameter =  mapper.readValue(String.format("{\"%s\":%s}", key,value), 
                    Parameter.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

选项 2:

@JsonIgnore
属性并为根 A
注册 
自定义序列化器/反序列化器

SimpleModule module = new SimpleModule();
module.addSerializer(A.class, new ASerializer());
module.addDeserializer(A.class, new ADeserializer());
mapper.registerModule(module);

不能在A类上面使用

@JsonSerialize
,因为ObjectMapper内部的序列化器和反序列化器也会使用这个注释,但是你需要将其设置为使用默认的序列化器/反序列化器,而不是递归地使用它本身。或者,如果您确实想要注释,您可以实现类似 https://stackoverflow.com/a/18405958/1032167 的内容

序列化器+反序列化器看起来像这样(未优化,只是概念证明):

    /************************ Serialization ************************/

public static class ASerializer extends JsonSerializer<A> {
    private static ObjectMapper m = new ObjectMapper();

    @Override
    public void serialize(A value, JsonGenerator gen,
                          SerializerProvider serializers) throws IOException {
        Map defaults = m.convertValue(value, Map.class);
        Map params = m.convertValue(value.getParameter(), Map.class);
        defaults.putAll(params);
        gen.writeObject(defaults);
    }

}

    /************************ Deserialization **********************/

public static class ADeserializer extends JsonDeserializer<A> {
    private static ObjectMapper m = new ObjectMapper();
    private static String[] subtipes = {"integerParam", "comboParam"};

    public ADeserializer() {
        m.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    }

    @Override
    public A deserialize(JsonParser p, DeserializationContext ctxt)
            throws IOException {

        TreeNode node = m.readTree(p);

        A a = m.convertValue(node, A.class);

        // hardcoded , probably can be done dynamically
        // with annotations inspection
        for (String key : subtipes) {
            TreeNode value = node.get(key);
            if (value != null) {
                String json = String.format("{\"%s\":%s}", key, value);
                a.setParameter(m.readValue(json, Parameter.class));
                break;
            }
        }

        return a;
    }
}

通用反序列化器很难编写。但根据问题正文,这个问题无论如何都是关于序列化的。


0
投票

也许为时已晚,但仍然为任何前来寻找的人发帖。 我设法使用 @JsonAnyGetter 的受控序列化解决了这个问题。 并使用具有不同 @JsonProperty 值属性的multiple setter 进行多态反序列化。

class A {
   Parameter parameter;

   @JsonProperty("integerParam") /* DESERIALIZE if integerParam type */
   public void setParameter(IntegerParameter parameter) {
       this.parameter = parameter;
   }
   @JsonProperty("comboParam") /* DESERIALIZE if comboParam type */
   public void setParameter(ComboParameter parameter) {
       this.parameter = parameter;
   }
   @JsonIgnore /*prevent serialization using default getter, this will wrap stuff into parameter*/
   public Parameter getParameter() {
       return parameter;
   }
   @JsonAnyGetter/*SERIALIZE: use any getter to add custom wrapper as per the child class type*/
   private Map<String, Object> parameterAsMap(){
       if (this.parameter instanceof IntegerParameter)
           return Map.of("integerParam",this.parameter);
       else
           return Map.of("comboParam",this.parameter);
   }
}

所有类型和子类型类都没有类型信息,即

abstract class Parameter {
    String regEx;
}
class IntegerParameter extends Parameter {
}
class ComboParameter extends Parameter {
    List<String> values;
}

最后我们得到如下解包的 Json:

{
  "integerParam" : {
    "regEx" : "regExIntVal"
  }
}

并且

{
  "comboParam" : {
    "regEx" : "regExComboVal",
    "values" : [ "X", "Y", "Z" ]
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.