JAXB,如何在解组时验证nillable和required字段 [英] JAXB, how to validate nillable and required field when unmarshalling

查看:667
本文介绍了JAXB,如何在解组时验证nillable和required字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对JAXB有一个小问题,但遗憾的是我无法找到答案。

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

我有一个类Customer,有2个字段 name city ,映射是使用注释完成的,并且两个字段都标记为必需且不可为空。

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);
    }
}

但是,当我提交此类XML文件时:

However, when I submit such XML file:

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

我将收到一个客户实例,两个字段都设置为null。

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?

要解组我使用:

JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) unmarshaller.unmarshal(in);


推荐答案

您需要使用架构进行验证。 JAXB无法自行进行验证。

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);

这篇关于JAXB,如何在解组时验证nillable和required字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆