JAXB条件绑定

时间:2013-04-22 11:56:32

标签: java json binding jaxb conditional

我有一个类:

@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"....}

如果状态==“已删除” - >仅绑定2个字段

{"objectsId":1,"status":"deleted"}

可以用JAXB吗? 感谢

1 个答案:

答案 0 :(得分:3)

注意:我是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"
}

我已打开以下增强请求,以使此用例更易于处理: