Jackson XML 标签解析器失败

Jackson XML parser fails when tags

Jackson XML 解析器在出现如下属性时失败:

<some-float-value fr:relevance="true">99</some-float-value>

错误日志如下所示:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.lang.Float` out of START_OBJECT token

如果我删除属性,那么字段看起来像这样,一切正常:

<some-float-value>99</some-float-value>

我要解析的class是这样的:

@JsonIgnoreProperties(ignoreUnknown = true)
public class Example {
    @JacksonXmlProperty(localName = "some-float-value")
    private Float someValue;
}

如果没有 fr 命名空间,@JsonIgnoreProperties(ignoreUnknown = true) 注释就足以忽略 relevance 属性,但不幸的是,情况并非如此:如果您想摆脱 xml 文件,你可以指示你的 XmlMapper 忽略它们传递自定义 XmlFactory 作为构造函数参数,如下所示:

XMLInputFactory input = new WstxInputFactory();
input.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.FALSE);
XmlMapper  mapper = new XmlMapper(new XmlFactory(input, new WstxOutputFactory()));
Example example = mapper.readValue(xml, Example.class);

您还必须使用 JacksonXmlRootElement 注释和 JacksonXmlText 注释修改 Example class,如下所示:

@JsonIgnoreProperties(ignoreUnknown = true)
@JacksonXmlRootElement(localName = "some-float-value")
public class Example {
    
    @JacksonXmlText
    private Float someValue;
}   

通过从 Jackson 版本 2.11.3 升级到 2.12.3 来解决