java - 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)
解决方案
这是你的问题:
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字段名。
推荐阅读
- c# - 允许在内部水平滚动 ScrollViewer 内垂直滚动外部 ScrollViewer
- python - AttributeError:“str”对象在尝试使用 writerow 时没有属性“keys”
- excel - 如何使用 Excel VBA 打开 Outlook excel 附件,在特定时间范围内发送到特定 Outlook 文件夹?
- php - 如何修复 Laravel 令牌不匹配 CSRF 错误
- r - 直方图严格从数据集的最小值开始,并且必须严格以数据集的最大值结束
- html - 带有 html/docx 输出的 R Markdown 文档,使用 LaTeX 包 bbm?
- java - 通过 Intent 将类传递给活动(崩溃)
- python-3.7 - 有时代码工作,有时它不起作用?请检查代码
- python - 为什么我的 keras LSTM 模型会陷入无限循环?
- reactjs - How to reset multiple counters with one button in React