Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

java - JAXB: how to make JAXB NOT to unmarshal empty string to 0

I have a DTO class with a field such as:

@XmlAttribute
@NotNull
private Integer number = null;

I'm trying to unmarshal xml such as

...  number=""  ...

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...