JAXB: how to make JAXB NOT to unmarshal empty string to 0(JAXB:如何使 JAXB 不将空字符串解组为 0)
问题描述
我有一个带有如下字段的 DTO 类:
I have a DTO class with a field such as:
@XmlAttribute
@NotNull
private Integer number = null;
我正在尝试解组 xml,例如
I'm trying to unmarshal xml such as
... number="" ...
我需要 nuber 字段保持为空,以便引发验证异常.相反,JAXB 将其解组为 0.我怎样才能让它正常运行?
I need the nuber field to stay null, so that a validation exception would be thrown. Instead JAXB unmarshals it as 0. How can I make it to behave correctly ?
推荐答案
有争议,它是行为正确.number=""
并不意味着 null,它是一个空字符串,JAXB 必须尝试正确处理它,它决定最接近 Integer 数据类型的空字符串的值为零.如果你想要一个 null
,那么应该完全省略 number
属性.
Arguable, it is behaving correctly. number=""
does not mean null, it's an empty String, and JAXB is having to try and handle that correctly, and it decides that the closest thing to empty string for an Integer data type is zero. If you wanted a null
, then the number
attribute should be omitted altogether.
如果你想自定义这个行为,你需要编写一个javax.xml.bind.annotation.adapters.XmlAdapter
的子类,它可以处理原始String和boundtype之间的转换(即在字符串和整数)以您想要的方式.然后,通过使用 @XmlJavaTypeAdapter
注释字段来连接该适配器.
If you want to customise this behaviour, you need to write a subclass of javax.xml.bind.annotation.adapters.XmlAdapter
which can handle the conversion between raw String and the boundtype (i.e. between String and Integer) in the way you want. You then wire up that adaptor by annotating the field with @XmlJavaTypeAdapter
.
这篇关于JAXB:如何使 JAXB 不将空字符串解组为 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JAXB:如何使 JAXB 不将空字符串解组为 0


- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01