杰克逊反序列化匿名复杂类型导致无法识别的字段“”

Jackson deserialize anonymous complex type results in Unrecognized field ""

我遇到以下异常:

Unrecognized field "" (class my.package.RequestParameter), not marked as ignorable (2 known properties: "value", "name"])
 at [Source: (StringReader); line: 1, column: 64] (through reference chain: my.package.RequestParameter[""])
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "" (class my.package.RequestParameter), not marked as ignorable (2 known properties: "value", "name"])

当我尝试反序列化以下条目时:

"<requestParameter name=\"myId\">5482973821</requestParameter>"

我的目标 Pojo:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
        "value"
})
@Getter
@Setter
@NoArgsConstructor
public class RequestParameter {
    @XmlValue
    protected String value;
    @XmlAttribute(name = "name")
    protected String name;
}

使用:

RequestParameter requestParameter = new XmlMapper().readValue(in, RequestParameter.class);

有人知道我错过了什么吗?感谢您的关注。

您可以在 class 中的 value 字段上使用 JacksonXmlText 注释:

@Getter
@Setter
@ToString
@NoArgsConstructor
public class RequestParameter {

    @XmlValue
    @JacksonXmlText //<-- the new annotation
    protected String value;
    @XmlAttribute(name = "name")
    protected String name;
}

RequestParameter requestParameter = mapper.readValue(msg, RequestParameter.class);
//it will print RequestParameter(value=5482973821, name=myId)
System.out.println(requestParameter);

请注意,如果您想序列化它,您将不会获得相同的起始xml,但它与您发布的代码的场景相同,因为name 字段将以不同于原始 xml 的方式序列化。