我在JAX-RS Web服务中使用JAXB(EclipseLink实现)。在XML请求中传递空元素时,会创建一个空对象。是否可以将JAXB设置为创建一个空对象?
示例XML:
<RootEntity>
<AttributeOne>someText</AttributeOne>
<EntityOne id="objectID" />
<EntityTwo />
</RootEntity>
当解组时,创建EntityOne的实例并将id属性设置为“objectID”,并使用null属性创建EntityTwo的实例。相反,我想为EntityTwo创建一个null对象,因为有一个空对象会导致JPA持久性操作出现问题。
答案 0 :(得分:0)
您可以使用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之一的每晚构建尝试此操作: