首页 > 解决方案 > XML:faxterxml 无法通过忽略 xml 属性反序列化 xml 元素

问题描述

我正在尝试使用 fastxml 库反序列化 XML,并且在解析 xml 属性期间遇到错误,如下所示。

豆子:

@XmlAccessorType(XmlAccessType.FIELD)
@Data
public class Product {
    public int id;
    public int id_manufacturer;
}

xml:

<product>
   <id><![CDATA[1]]></id>
   <id_manufacturer xlink:href="http://localhost:8080/api/manufacturers/1"><![CDATA[1]]></id_manufacturer>
</product>

依赖:

implementation group: 'com.fasterxml.jackson.dataformat', name: 'jackson-dataformat-xml', version: '2.7.4'

执行:

XmlMapper xmlMapper = new XmlMapper();
xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
System.out.println(xmlMapper.readValue(XML_STRING, Product.class));

例外:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `int` from Object value (token `JsonToken.START_OBJECT`)
 at [Source: (File); line: 4, column: 81] (through reference chain: come.has.you.are.Product["id_manufacturer"])

有任何想法吗 ?当然,我已经尝试过注释@JsonIgnoreProperties(ignoreUnknown = true)

标签: javaxmlfasterxml

解决方案


这是你的问题: CDATA是一个String价值,而不是一个int价值。
注意:CDATA 是“字符数据”的缩写。

选项1:改变你的Product班级。例如,

@XmlAccessorType(XmlAccessType.FIELD)
@Data
public class Product2
{
    public String id;
    public String id_manufacturer;
}

选项 2:添加字符串设置器

@XmlAccessorType(XmlAccessType.FIELD)
@Data
public class Product
{
    public int id;
    
    @JsonProperty("id_manufacturer")
    public int idManufacturer;
    
    public void setId(final String value)
    {
        if (StringUtils.isNumeric(value))
        {
            id = Integer.valueOf(value).intValue();
        } 
    }
    
    public void setIdManufacturer(final String value)
    {
        if (StringUtils.isNumeric(value))
        {
            idManufacturer = Integer.valueOf(value).intValue();
        }
    } 
}

注意:id_manufacturer是标签名,但不是java字段名。


推荐阅读