Cralbert
Cralbert

Reputation: 23

JAXB How to parse empty value string to null Integer

I have the next problem. I have to define the attribute of XLS as Integer. When the XMLAdapter (define for me) receives the value, instead of receiving a null or empty, you receive a 0 (because de Integer parse emty '' value to 0), which is incorrect in my case. How do I know if this value comes from a "" or a 0? I need If the attribute value is "", the value should be Null; if 0, should be 0. For me it is a bug in JAXB. I read:
JAXB: how to make JAXB NOT to unmarshal empty string to 0
But its not a solution for me.
What can I do?!
I defined mi XMLAdapter:

public class IntegerAdapter extends XmlAdapter<Integer, Integer> {
    @Override
    public Integer marshal(Integer arg0) throws Exception {
        return arg0;
    }
    @Override
    public Integer unmarshal(Integer v) throws Exception {
        return v;
    }
}

I dont define it like XmlAdapter<String, Integer>, because the definition of the XLS attribute must be Integer. Thanks!

Upvotes: 2

Views: 2205

Answers (1)

bdoughan
bdoughan

Reputation: 148977

You should use the following instead:

XmlAdapter<String, Integer>

I dont define it like XmlAdapter<String, Integer>, because the definition of the XLS attribute must be Integer.

You can use the @XmlSchemaType annotation to set the schema type you want.

@XmlJavaTypeAdapter(IntegerAdapter.class)
@XmlSchemaType(name="integer")
public Integer getAge() {
    return age;
}

Upvotes: 2

Related Questions