我有一个类:
@XmlRootElement
Class ClassA {
public long objectId;
public String status;
public String property1;
......
}
我希望 JAXB 的 JSON 输出以属性“status”为条件。例如:
if status != "deleted"-> 绑定(bind)所有字段
{"objectId":1,"status":"new","property1":"value1","property2":"value2","prop3":"val3"....}
if status == "deleted"-> 只绑定(bind) 2 个字段
{"objectsId":1,"status":"deleted"}
这可能与 JAXB 相关吗??? 谢谢
最佳答案
注意:我是 EclipseLink JAXB (MOXy) JAXB (JSR-222) 的领导和成员专家组。
您可以使用我们在 EclipseLink 2.5 中添加到 MOXy 的对象图扩展来处理此用例。您可以从以下位置下载夜间构建:
A 级
我们将使用 MOXy 的对象图扩展来指定可以编码的值的子集。
- http://blog.bdoughan.com/2013/03/moxys-object-graphs-inputoutput-partial.html
- http://blog.bdoughan.com/2013/03/moxys-object-graphs-partial-models-on.html
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
属性(property)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"
}
我已经打开了以下增强请求,使这个用例更容易处理:
关于java - JAXB 条件绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16146559/