JAXB:如何让 JAXB 不将空字符串解组为 0 [英] JAXB: how to make JAXB NOT to unmarshal empty string to 0

查看:45
本文介绍了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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆