EclipseLink JAXB (MOXy)의 @XmlNamedObjectGraph
확장을 사용하여이 사용 사례를 지원할 수 있습니다. @XmlNamedObjectGraph
을 사용하면 데이터에 여러 개의보기를 만들 수 있습니다.
사람
우리는 단지 2 개 필드 (firstName
및 lastName
)를 노출하는 Person
클래스 뷰를 만들 @XmlNamedObjectGraph
를 사용하여 아래.
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;
}
}
우리는 우리가 MarshallerProperties.OBJECT_GRAPH
속성을 사용하여 Marshaller
에 적용하려는 명명 된 객체 그래프를 지정합니다 아래의 데모 코드에서 데모
. 다음은 출력
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' 클래스는 객체는 XML에 정렬 화되는 특성을 제한 할 나타납니다 위치에 따라 속성'clientId','email','firstName','lastName'하고있다? –
예. 정확히 필요한 부분입니다. – yglodt