注意: 我是EclipseLink JAXB (MOXy)负责人,也是JAXB (JSR-222)专家组的成员。
您可以使用我们在 EclipseLink 2.5 中添加到 MOXy 的对象图扩展来处理这个用例。您可以从以下位置下载每晚构建:
A类
我们将使用 MOXy 的对象图扩展来指定可以编组的值的子集。
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.*;
@XmlRootElement
@XmlNamedObjectGraph(
name="deleted",
attributeNodes = {
@XmlNamedAttributeNode("objectId"),
@XmlNamedAttributeNode("status")
}
)
public class ClassA {
public long objectId;
public String status;
public String property1;
}
jaxb.properties
要将 MOXy 指定为您的 JAXB 提供程序,您需要包含一个jaxb.properties
在与域模型相同的包中调用的文件,其中包含以下条目(请参阅: http ://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as -你的.html):
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
演示
在下面的演示代码中,我们将MarshallerProperties.OBJECT_GRAPH
属性设置为deleted
onMarshaller
如果status
on 的实例ClassA
等于deleted
。
import java.util.*;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import org.eclipse.persistence.jaxb.JAXBContextProperties;
import org.eclipse.persistence.jaxb.MarshallerProperties;
public class Demo {
public static void main(String[] args) throws Exception {
Map<String, Object> properties = new HashMap<String, Object>(2);
properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
JAXBContext jc = JAXBContext.newInstance(new Class[] {ClassA.class}, properties);
ClassA classA = new ClassA();
classA.objectId = 1;
classA.property1 = "value1";
classA.status = "new";
marshal(jc, classA);
classA.status = "deleted";
marshal(jc, classA);
}
private static void marshal(JAXBContext jc, ClassA classA) throws Exception {
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
if("deleted".equals(classA.status)) {
marshaller.setProperty(MarshallerProperties.OBJECT_GRAPH, "deleted");
}
marshaller.marshal(classA, System.out);
}
}
输出
下面是运行演示代码的输出。当status
等于deleted
该property1
值时不进行编组。
{
"objectId" : 1,
"status" : "new",
"property1" : "value1"
}
{
"objectId" : 1,
"status" : "deleted"
}
我已打开以下增强请求以使此用例更易于处理: