JAXB how to check valid and required field when disassembling


I have a little problem with JAXB, but unfortunately I could not find the answer.

I have a Customer class, with two name and city fields, the mapping is done using annotations, and both fields are marked as required, 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 this XML file:

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

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

There should be no exception to check, or am I missing something in the display?

To unleash, I use:

 JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); Customer customer = (Customer) unmarshaller.unmarshal(in); 
+4
source share
2 answers

You need to use the circuit to check. JAXB cannot perform 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); 
+4
source

You can automatically generate a circuit at runtime and use it for validation. This will do the job:

 JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); generateAndSetSchema(unmarshaller); Customer customer = (Customer) unmarshaller.unmarshal(in); private void generateAndSetSchema(Unmarshaller unmarshaller) { // generate schema ByteArrayStreamOutputResolver schemaOutput = new ByteArrayStreamOutputResolver(); jaxbContext.generateSchema(schemaOutput); // load schema ByteArrayInputStream schemaInputStream = new ByteArrayInputStream(schemaOutput.getSchemaContent()); SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = sf.newSchema(new StreamSource(schemaInputStream)); // set schema on unmarshaller unmarshaller.setSchema(schema); } private class ByteArrayStreamOutputResolver extends SchemaOutputResolver { private ByteArrayOutputStream schemaOutputStream; public Result createOutput(String namespaceURI, String suggestedFileName) throws IOException { schemaOutputStream = new ByteArrayOutputStream(INITIAL_SCHEMA_BUFFER_SIZE); StreamResult result = new StreamResult(schemaOutputStream); // We generate single XSD, so generator will not use systemId property // Nevertheless, it validates if it not null. result.setSystemId(""); return result; } public byte[] getSchemaContent() { return schemaOutputStream.toByteArray(); } } 
+2
source

Source: https://habr.com/ru/post/1479788/


All Articles