1

我有一个像这样的课程:

@XmlRootElement 
Class ClassA {

public long objectId;

public String status;

public String property1;

......
}

我希望 JAXB 的 JSON 输出以属性“状态”为条件。前任:

if status != "deleted" -> 绑定所有字段

{"objectId":1,"status":"new","property1":"value1","property2":"value2","prop3":"val3"....}

if status == "deleted" -> 只绑定 2 个字段

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

这可能与JAXB有关吗?谢谢

4

1 回答 1

3

注意: 我是EclipseLink JAXB (MOXy)负责人,也是JAXB (JSR-222)专家组的成员。

您可以使用我们在 EclipseLink 2.5 中添加到 MOXy 的对象图扩展来处理这个用例。您可以从以下位置下载每晚构建:

A类

我们将使用 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 -你的.html):

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

演示

在下面的演示代码中,我们将MarshallerProperties.OBJECT_GRAPH属性设置为deletedonMarshaller如果statuson 的实例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等于deletedproperty1值时不进行编组。

{
   "objectId" : 1,
   "status" : "new",
   "property1" : "value1"
}
{
   "objectId" : 1,
   "status" : "deleted"
}

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

于 2013-04-23T20:26:34.957 回答