[英]JAXB conditioned binding
我有一個類:
@XmlRootElement
Class ClassA {
public long objectId;
public String status;
public String property1;
......
}
我希望JAXB的JSON輸出以屬性“status”為條件。 例如:
if status!=“deleted” - >綁定所有字段
{"objectId":1,"status":"new","property1":"value1","property2":"value2","prop3":"val3"....}
如果status ==“deleted” - >僅綁定2個字段
{"objectsId":1,"status":"deleted"}
這可能與JAXB ??? 謝謝
注意:我是EclipseLink JAXB(MOXy)的負責人,也是JAXB(JSR-222)專家組的成員。
您可以使用我們在EclipseLink 2.5中添加到MOXy的對象圖擴展來處理此用例。 您可以從以下位置下載每晚構建:
ClassA的
我們將使用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-your.html ):
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
演示
在演示代碼下面我們將設置MarshallerProperties.OBJECT_GRAPH
屬性deleted
上Marshaller
如果status
上的實例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"
}
我打開了以下增強請求,以使這個用例更容易處理:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.