【问题标题】:Deserialization JAXBElement with jackson使用杰克逊反序列化 JAXBElement
【发布时间】:2026-02-04 17:50:01
【问题描述】:

我有一个这样的模型:

public class Type {

    @XmlElementRef(name = "ConversationId", namespace = "...", type = JAXBElement.class, required = false)
    protected JAXBElement<String> conversationId;
}

和json的一部分:

  "conversationId": {
    "declaredType": "java.lang.String",
    "globalScope": false,
    ...,
    "value": "ABC000000001"
  },

我尝试使用此映射器进行反序列化:

public static interface JAXBElementMixin {
    @JsonValue
    Object getValue();
}

ObjectMapper mapper = new ObjectMapper();
JaxbAnnotationIntrospector jaxbAnnotationIntrospector=new JaxbAnnotationIntrospector(mapper.getTypeFactory());
JacksonAnnotationIntrospector jacksonAnnotationIntrospector=new JacksonAnnotationIntrospector();
mapper.setAnnotationIntrospector(AnnotationIntrospector.pair(jaxbAnnotationIntrospector, jacksonAnnotationIntrospector));

mapper.addMixIn(JAXBElement.class, JAXBElementMixin.class);

但无论如何,我的程序运行不佳:

com.fasterxml.jackson.databind.JsonMappingException:没有找到适合类型[简单类型,类 javax.xml.bind.JAXBElement] 的构造函数:无法从 JSON 对象实例化(缺少默认构造函数或创建者,或者可能需要添加/启用类型信息?)

我想阅读一些关于 mixins 的文档,但是 jackson 的官方网站上有过时的信息,我使用的是 2.5.1 版本

【问题讨论】:

  • 我也有同样的问题,找到解决办法了吗?

标签: java json serialization jaxb jackson


【解决方案1】:

我也遇到了同样的问题,终于解决了。为了使它起作用,需要做两件事:

  1. Mixin 类必须在单独的文件中,而不是内部或 匿名类。
  2. Mixin 类必须在不同的包中, 即如果创建映射器的代码在包中 com.foo.bar 那么 Mixin 类不能在这个包中。

这是我的代码:

package com.foo.bar;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;

@JsonIgnoreProperties(value = {"globalScope", "typeSubstituted", "nil", "scope"})
public abstract class JAXBElementMixIn<T> extends JAXBElement<T> {
    @JsonCreator
    public JAXBElementMixIn(@JsonProperty("name") QName name,
                            @JsonProperty("declaredType") Class<T> declaredType,
                            @JsonProperty("value") T value) {
        super(name, declaredType, value);
    }
}

以及使用它的代码:

package x.y.z;

...

ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(JAXBElement.class, JAXBElementMixIn.class);

【讨论】: