JAXB:如何使 JAXB 不将空字符串解组为 0

2022-01-19 00:00:00 java jaxb unmarshalling

我有一个带有如下字段的 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.

相关文章