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


基础教程推荐
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 降序排序:Java Map 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01