猿问

JAXB:在特殊值的情况下忽略元素序列化(例如“null”或“Double.NaN”)

我想用JAXB. 该对象具有可能具有特殊值的实例变量,例如null或 在另一种情况下Double.NaN。


如果它具有这个特殊值,我怎么能只忽略实例变量呢?


这可能吗?


@XmlRootElement

@XmlAccessorType(XmlAccessType.FIELD)

public class MyClass {


   private double value;

   private Object object;


   public void setValue(double value){this.value = value;}

   public double getValue(){return value;}


   public void setObject(Object object){this.object = object;}

   public Object getObject(){return object;}


}

value所以在存在Double.NaN和object不存在的情况下null我想得到


<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<MyClass>

  <object>

    ...

  </object>

</MyClass>

在另一种情况下,如果value不是Double.NaN,我object想得到null


<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<MyClass>

  <value>1.0</value>

</MyClass>


犯罪嫌疑人X
浏览 191回答 1
1回答

缥缈止盈

默认情况下,空值不会生成 XML,因此您对该object属性的要求已经得到处理。对于特殊double值,创建一个专门的方法来产生 XML值,并抑制or到 XMLvalue的正常映射。valuegetValue()@XmlTransient这可以通过使用 注释或使用 禁用自动属性选择来完成XmlAccessType.NONE,因此只有带注释的属性才会映射到 XML。这是使用第二种方法的示例:@XmlRootElement@XmlAccessorType(XmlAccessType.NONE)public class MyClass {&nbsp; &nbsp; private double value;&nbsp; &nbsp; private Foo foo;&nbsp; &nbsp; public MyClass() {&nbsp; &nbsp; }&nbsp; &nbsp; public MyClass(double value, Foo foo) {&nbsp; &nbsp; &nbsp; &nbsp; this.value = value;&nbsp; &nbsp; &nbsp; &nbsp; this.foo = foo;&nbsp; &nbsp; }&nbsp; &nbsp; public void setValue(double value){this.value = value;}&nbsp; &nbsp; public double getValue(){return this.value;}&nbsp; &nbsp; public void setFoo(Foo foo){this.foo = foo;}&nbsp; &nbsp; @XmlElement() public Foo getFoo(){return this.foo;}&nbsp; &nbsp; @XmlElement(name = "value")&nbsp; &nbsp; public Double getXmlValue() {&nbsp; &nbsp; &nbsp; &nbsp; if (Double.isFinite(this.value))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return this.value;&nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; }}public class Foo {&nbsp; &nbsp; @XmlElement()&nbsp; &nbsp; public String getBar() { return "Test"; }}测试JAXBContext jaxbContext = JAXBContext.newInstance(MyClass.class);Marshaller marshaller = jaxbContext.createMarshaller();marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);marshaller.marshal(new MyClass(Math.PI, null), System.out);marshaller.marshal(new MyClass(Double.NaN, new Foo()), System.out);输出<?xml version="1.0" encoding="UTF-8" standalone="yes"?><myClass>&nbsp; &nbsp; <value>3.141592653589793</value></myClass><?xml version="1.0" encoding="UTF-8" standalone="yes"?><myClass>&nbsp; &nbsp; <foo>&nbsp; &nbsp; &nbsp; &nbsp; <bar>Test</bar>&nbsp; &nbsp; </foo></myClass>注意<foo>第一个中缺少 ,因为它是null,<value>第二个中缺少,因为该NaN值作为null值返回。正常使用调用 时MyClass仍会获得值。NaNgetValue()
随时随地看视频慕课网APP

相关分类

Java
我要回答