如果您使用的是 EclipseLink 2.5.0,您可以@XmlNamedObjectGraphs在此用例中利用 MOXy 的扩展。可以从以下链接下载 EclipseLink 2.5.0 候选版本:
领域模型(Foo)
该@XmlNamedObjectGraph扩展允许您指定可以与编组和解组一起使用的映射子集。
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.*;
@XmlNamedObjectGraphs({ 
    @XmlNamedObjectGraph(
        name="a",
        attributeNodes={
            @XmlNamedAttributeNode("a"),
            @XmlNamedAttributeNode("ab"),
            @XmlNamedAttributeNode("ac")
        }
    ),
    @XmlNamedObjectGraph(
        name="b",
        attributeNodes={
            @XmlNamedAttributeNode("ab"),
            @XmlNamedAttributeNode("bc")
        }
    ),
    @XmlNamedObjectGraph(
        name="c",
        attributeNodes={
            @XmlNamedAttributeNode("bc"),
            @XmlNamedAttributeNode("c"),
            @XmlNamedAttributeNode("ac")
        }
    )
})
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Foo {
    int a;
    int ab;
    int bc;
    int c;
    int ac;
}
演示
在下面的演示代码中,我们将填充一个实例,Foo然后利用我们定义的对象图以四种不同的方式输出它。
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.MarshallerProperties;
public class Demo {
    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Foo.class);
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        Foo foo = new Foo();
        foo.a = 1;
        foo.ab = 2;
        foo.ac = 3;
        foo.bc = 4;
        foo.c = 5;
        // Marshal to XML - Everything
        marshaller.marshal(foo, System.out);
        // Marshal to XML - Application A
        marshaller.setProperty(MarshallerProperties.OBJECT_GRAPH, "a");
        marshaller.marshal(foo, System.out);
        // Marshal to JSON - Application B
        marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
        marshaller.setProperty(MarshallerProperties.OBJECT_GRAPH, "b");
        marshaller.marshal(foo, System.out);
        // Marshal to JSON - Application C
        marshaller.setProperty(MarshallerProperties.OBJECT_GRAPH, "c");
        marshaller.marshal(foo, System.out);
    }
}
输出
以下是我们从演示代码中生成的四种不同视图。Foo请记住,我们每次编组完全相同的实例并填充相同的数据。
<?xml version="1.0" encoding="UTF-8"?>
<foo>
   <a>1</a>
   <ab>2</ab>
   <bc>4</bc>
   <c>5</c>
   <ac>3</ac>
</foo>
<?xml version="1.0" encoding="UTF-8"?>
<foo>
   <a>1</a>
   <ab>2</ab>
   <ac>3</ac>
</foo>
{
   "foo" : {
      "ab" : 2,
      "bc" : 4
   }
}{
   "foo" : {
      "bc" : 4,
      "c" : 5,
      "ac" : 3
   }
}
了解更多信息