I would like to configure JAXB so that it trims whitespaces on all string fields
I saw the following answer : How to configure JAXB so it trims whitespaces when unmarshalling tag value?
But I do not want to have to annotate all string fields as per the suggested answer
@XmlElement(required=true)
@XmlJavaTypeAdapter(MyNormalizedStringAdapter.class)
String name;
Thanks!
Create a XmlAdapter.
package com.foo.bar;
public class StringTrimAdapter extends XmlAdapter<String, String> {
@Override
public String unmarshal(String v) throws Exception {
if (v == null)
return null;
return v.trim();
}
@Override
public String marshal(String v) throws Exception {
if (v == null)
return null;
return v.trim();
}
}
Create a package-info.java
file in com.foo.bar
.
Add the following to the package-info.java
file
@XmlJavaTypeAdapter(value=StringTrimAdapter.class,type=String.class)
package com.foo.bar;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
StringTrimAdapter
to all String
fields in com.foo.bar
without any extra annotations.EDIT
Do note that if the package level annotation is too expansive for you, you could always apply a @XmlJavaTypeAdapter
annotation to classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With