我对JAXB有一个小问题,但不幸的是我无法找到答案。
我有一个类Customer,有2个字段 name 和 city ,映射是使用注释完成的,并且这两个字段都标记为必需而不是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);
}
}
但是,当我提交这样的XML文件时:
<customer>
<city>UNKNOWN</city>
</customer>
我将收到一个Customer实例,其中两个字段都设置为null。
不应该有验证异常,或者我在映射中遗漏了什么?
要解组我使用:
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) unmarshaller.unmarshal(in);
答案 0 :(得分:5)
您需要使用架构进行验证。 JAXB无法自行进行验证。
SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(ClassUtils.getDefaultClassLoader().getResource(schemaPath));
unmarshaller.setSchema(schema);
答案 1 :(得分:2)
您可以在运行时自动生成模式并将其用于验证。 这将完成这项工作:
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's not null.
result.setSystemId("");
return result;
}
public byte[] getSchemaContent() {
return schemaOutputStream.toByteArray();
}
}