NOT将空字符串解组为0

NOT将空字符串解组为0

本文介绍了JAXB:如何使JAXB NOT将空字符串解组为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字段保持为null,以便抛出验证异常。相反,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 ?

推荐答案

Arguable,它 行为正确。 number =并不意味着null,它是一个空字符串,并且JAXB必须尝试正确处理它,并且它决定了最接近空字符串的东西整数数据类型为零。如果你想要一个 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 的子类,它可以处理转换在原始字符串和boundtype之间(即在String和Integer之间)以您希望的方式。然后,通过使用 @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 NOT将空字符串解组为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 07:56