Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAXB, how to validate nillable and required field when unmarshalling

Tags:

java

xml

jaxb

I have a small problem with JAXB, but unfortunately I was not able to find answer.

I have a class Customer, with 2 fields name and city, the mapping is done using annotations and both fields are marked as required and not nillable.

@XmlRootElement(name = "customer")
public class Customer {

    enum City {
        PARIS, LONDON, WARSAW
    }

    @XmlElement(name = "name", required = true, nillable = false)
    public String name;
    @XmlElement(name = "city", required = true, nillable = false)
    public City city;

    @Override
    public String toString(){
        return String.format("Name %s, city %s", name, city);
    }
}

However, when I submit such XML file:

<customer>
    <city>UNKNOWN</city>
</customer>

I will receive a Customer instance with both fields set to null.

Shouldn't there be a validation exception or am I missing something in the mapping?

To unmarshal I use:

JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) unmarshaller.unmarshal(in);
like image 429
zibi Avatar asked May 08 '13 17:05

zibi


People also ask

What is JAXB marshalling and unmarshalling?

JAXB definitionsMarshalling is the process of transforming Java objects into XML documents. Unmarshalling is the process of reading XML documents into Java objects.

How do you ignore a field in XML response?

Ignore XML Attribute. You can specify ignore="true" or ignore="false". The default value is false. Specifying ignore="false" has no effect on the attribute value assigned when an object of the type specified in the rule is created and no effect on the constraints.

Which annotation is used to map a Java class object to XML element?

The JAXB annotations defined in the javax. xml. bind. annotations package can be used to customize Java program elements to XML schema mapping.


1 Answers

You need to use the schema to validate. JAXB can't do validation on its own.

SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(ClassUtils.getDefaultClassLoader().getResource(schemaPath));
unmarshaller.setSchema(schema);
like image 125
dkaustubh Avatar answered Nov 12 '22 13:11

dkaustubh