繁体   English   中英

使用JAXB创建Null对象解组空元素

[英]Create Null Object Unmarshalling Empty Element with JAXB

我在JAX-RS Web服务中使用JAXB(EclipseLink实现)。 在XML请求中传递空元素时,将创建一个空对象。 是否可以将JAXB设置为创建空对象?

XML示例:

<RootEntity>
    <AttributeOne>someText</AttributeOne>
    <EntityOne id="objectID" />
    <EntityTwo />
</RootEntity>

取消编组时,将创建EntityOne的实例,并将id属性设置为“ objectID”,并使用空属性创建EntityTwo的实例。 取而代之的是,我想要EntityTwo的空对象,因为拥有空对象会导致我的JPA持久性操作出现问题。

您可以使用MOXy的NullPolicy指定此行为。 您将需要创建DescriptorCustomizer来修改基础映射。 别担心,这比听起来容易,我将在下面演示:

import org.eclipse.persistence.config.DescriptorCustomizer;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.oxm.mappings.XMLCompositeObjectMapping;
import org.eclipse.persistence.oxm.mappings.nullpolicy.XMLNullRepresentationType;

public class RootEntityCustomizer implements DescriptorCustomizer {

    @Override
    public void customize(ClassDescriptor descriptor) throws Exception {
        XMLCompositeObjectMapping entityTwoMapping = (XMLCompositeObjectMapping) descriptor.getMappingForAttributeName("entityTwo");

        entityTwoMapping.getNullPolicy().setNullRepresentedByEmptyNode(true);
        entityTwoMapping.getNullPolicy().setMarshalNullRepresentation(XMLNullRepresentationType.EMPTY_NODE);
    }

}

下面是如何将定制程序与模型类相关联:

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import org.eclipse.persistence.oxm.annotations.XmlCustomizer;

@XmlRootElement(name="RootEntity")
@XmlCustomizer(RootEntityCustomizer.class)
public class RootEntity {

    private String attributeOne;
    private Entity entityOne;
    private Entity entityTwo;

    @XmlElement(name="AttributeOne")
    public String getAttributeOne() {
        return attributeOne;
    }

    public void setAttributeOne(String attributeOne) {
        this.attributeOne = attributeOne;
    }

    @XmlElement(name="EntityOne")
    public Entity getEntityOne() {
        return entityOne;
    }

    public void setEntityOne(Entity entityOne) {
        this.entityOne = entityOne;
    }

    @XmlElement(name="EntityTwo")
    public Entity getEntityTwo() {
        return entityTwo;
    }

    public void setEntityTwo(Entity entityTwo) {
        this.entityTwo = entityTwo;
    }

}

在下一版的MOXy(2.2)中,您将可以通过注释来执行此操作。

@XmlElement(name="EntityTwo")
@XmlNullPolicy(emptyNodeRepresentsNull=true,
              nullRepresentationForXml=XmlMarshalNullRepresentation.EMPTY_NODE)
public Entity getEntityTwo() {
    return entityTwo;
}

您现在可以使用每晚EclipseLink 2.2.0之一进行尝试:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM