EclipseLink JAXB (MOXy)当前不提供一种机制来选择性地指示每个编组操作中包含哪些字段/属性。这听起来像是一个有趣的用例。如果您可以使用以下链接将其作为增强请求输入,我将不胜感激:
下面是一个示例,说明如何通过利用JAXB (JSR-222)在值为 null 时不会编组元素 XmlAdapter
的事实来使用有状态来实现此用例(请参阅: http ://blog.bdoughan.com /2012/04/binding-to-json-xml-handling-null.html)。
场适配器
由于我们要利用有状态的 XmlAdapters,我们将需要每个字段一个。由于我们所有的 XmlAdapter 都将执行相同的逻辑,我们可以创建一个其他人可以扩展的超类。
package forum13094195;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class FieldAdapter<T> extends XmlAdapter<T, T> {
private boolean include;
public FieldAdapter() {
this.include = true;
}
public FieldAdapter(boolean include) {
this.include = include;
}
@Override
public T marshal(T value) throws Exception {
if(include) {
return value;
}
return null;
}
@Override
public T unmarshal(T value) throws Exception {
return value;
}
}
Field1适配器
package forum13094195;
public class Field1Adapter extends FieldAdapter<String> {
public Field1Adapter() {}
public Field1Adapter(boolean include) {
super(include);
}
}
Field2适配器
package forum13094195;
public class Field2Adapter extends FieldAdapter<Integer>{
public Field2Adapter() {}
public Field2Adapter(boolean include) {
super(include);
}
}
Field3适配器
package forum13094195;
public class Field3Adapter extends FieldAdapter<String> {
public Field3Adapter() {}
public Field3Adapter(boolean include) {
super(include);
}
}
商人
@XmlJavaTypeAdapter
注释用于在字段/属性上指定一个XmlAdapter
。
package forum13094195;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Merchant {
@XmlJavaTypeAdapter(Field1Adapter.class)
String field1;
@XmlJavaTypeAdapter(Field2Adapter.class)
int field2;
@XmlJavaTypeAdapter(Field3Adapter.class)
String field3;
}
演示
下面的演示代码演示了如何XmlAdapter
在Marshaller
.
package forum13094195;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Merchant.class);
Merchant merchant = new Merchant();
merchant.field1 = "A";
merchant.field2 = 2;
merchant.field3 = "C";
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(merchant, System.out);
marshaller.setAdapter(new Field1Adapter(false));
marshaller.setAdapter(new Field2Adapter(false));
marshaller.setAdapter(new Field3Adapter(true));
marshaller.marshal(merchant, System.out);
}
}
输出
下面是运行演示代码的输出。默认情况下,整个对象被编组。编组的第二个文档不包含我们排除的字段。
<?xml version="1.0" encoding="UTF-8"?>
<merchant>
<field1>A</field1>
<field2>2</field2>
<field3>C</field3>
</merchant>
<?xml version="1.0" encoding="UTF-8"?>
<merchant>
<field3>C</field3>
</merchant>