且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-10-15 09:02:34

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

You can specify this behaviour using MOXy's NullPolicy. You will need to create a DescriptorCustomizer to modify the underlying mappings. Don't worry it's easier than it sounds, I'll demonstrate below:

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

}

以下是关联定制器的方法与您的模型类:

Below is how you associate the customizer with your model class:

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)你可以通过注释来做到这一点。

In the next version of MOXy (2.2) you will be able to do this via annotations.

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

您现在可以使用EclipseLink 2.2.0夜间版本之一尝试:

You can try this now with one of the EclipseLink 2.2.0 nightly builds:

  • http://www.eclipse.org/eclipselink/downloads/nightly.php