您可以使用EclipseLink JAXB (MOXy)的@XmlNamedObjectGraph
扩展名来支持此用例。 @XmlNamedObjectGraph
允许您执行的操作是在您的数据上创建多个视图。
人
下面我们将用@XmlNamedObjectGraph
创建的Person
类只公开2场(firstName
和lastName
)的景色。
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.*;
@XmlNamedObjectGraph(
name = "simple",
attributeNodes = {
@XmlNamedAttributeNode("firstName"),
@XmlNamedAttributeNode("lastName")
}
)
@XmlAccessorType(XmlAccessType.FIELD)
public class Person {
private int clientId;
private String firstName;
private String lastName;
private String email;
public void setClientId(int clientId) {
this.clientId = clientId;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setEmail(String email) {
this.email = email;
}
}
政策
我们也将在Policy
类使用@XmlNamedObjectGraph
。它说,对于userCreated
字段,应用我们在Person
类中定义的名为simple
的命名对象图。
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@XmlNamedObjectGraph(
name = "policy",
attributeNodes = {
@XmlNamedAttributeNode(value = "userCreated", subgraph = "simple"),
@XmlNamedAttributeNode("client")
}
)
public class Policy {
private Person userCreated;
private Person client;
public void setUserCreated(Person userCreated) {
this.userCreated = userCreated;
}
public void setClient(Person client) {
this.client = client;
}
}
演示
在演示代码下面我们将指定我们想要在Marshaller
使用MarshallerProperties.OBJECT_GRAPH
属性应用的命名对象图。
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(Policy.class);
Person person = new Person();
person.setClientId(1234);
person.setFirstName("John");
person.setLastName("Doe");
person.setEmail("[email protected]");
Policy policy = new Policy();
policy.setClient(person);
policy.setUserCreated(person);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(MarshallerProperties.OBJECT_GRAPH, "policy");
marshaller.marshal(policy, System.out);
}
}
输出
下面是从运行演示代码的输出:
<?xml version="1.0" encoding="UTF-8"?>
<policy>
<userCreated>
<firstName>John</firstName>
<lastName>Doe</lastName>
</userCreated>
<client>
<clientId>1234</clientId>
<firstName>John</firstName>
<lastName>Doe</lastName>
<email>[email protected]</email>
</client>
</policy>
更多信息
的'Person'类具有'clientId','email','firstName','lastName'并基于该对象似乎要限制哪些属性编组到XML? –
是的,这正是我需要的 – yglodt