示范代码
以下演示代码将用于Java模型的所有不同版本。 它只是将一个集合设置为null,第二个设置为空列表,第三个设置为填充列表。
package package blog.xmlelementwrapper;
import java.util.ArrayList;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Root.class);
Root root = new Root();
root.nullCollection = null;
root.emptyCollection = new ArrayList<String>();
root.populatedCollection = new ArrayList<String>();
root.populatedCollection.add('foo');
root.populatedCollection.add('bar');
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);
}
}
映射1-默认
JAXB模型不需要任何注释(请参见JAXB –不需要注释 )。 首先,我们将了解集合属性的默认行为。
package blog.xmlelementwrapper;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
List<String> nullCollection;
List<String> emptyCollection;
List<String> populatedCollection;
}
检查输出,我们看到对应于nullCollection和emptyCollection字段的输出是相同的。 这意味着使用默认映射,我们无法往返实例。 对于非编组用例, nullCollection和EmptyCollection的值将是该类将其初始化为的字段的值(在这种情况下为null)。
<?xml version='1.0' encoding='UTF-8'?>
<root>
<populatedCollection>foo</populatedCollection>
<populatedCollection>bar</populatedCollection>
</root>
映射#2 – @XmlElementWrapper
@XmlElementWrapper批注用于在集合的内容周围添加分组元素。 除了更改XML表示的外观外,它还使我们能够区分null和空集合。
package blog.xmlelementwrapper;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
@XmlElementWrapper
List<String> nullCollection;
@XmlElementWrapper
List<String> emptyCollection;
@XmlElementWrapper
List<String> populatedCollection;
}
空集合的表示形式保持不变,但XML文档中不存在。 对于空集合,我们看到仅分组元素被整理。 由于null和empty的表示形式不同,因此我们可以往返使用该用例。
<?xml version='1.0' encoding='UTF-8'?>
<root>
<emptyCollection/>
<populatedCollection>
<populatedCollection>foo</populatedCollection>
<populatedCollection>bar</populatedCollection>
</populatedCollection>
</root>
映射#3 – @XmlElementWrapper(nillable = true)
@XmlElementWrapper批注上的nillable属性可用于更改null集合的XML表示形式。
package blog.xmlelementwrapper;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
@XmlElementWrapper(nillable=true)
List<String> nullCollection;
@XmlElementWrapper(nillable=true)
List<String> emptyCollection;
@XmlElementWrapper(nillable=true)
List<String> populatedCollection;
}
现在,所有三个字段都存在分组元素。 xsi:nil属性用于指示nullCollection字段为null。 像以前的映射一样,此映射可以往返。
<?xml version='1.0' encoding='UTF-8'?>
<root>
<nullCollection
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xsi:nil='true'/>
<emptyCollection/>
<populatedCollection>
<populatedCollection>foo</populatedCollection>
<populatedCollection>bar</populatedCollection>
</populatedCollection>
</root>
参考: JAXB –在Java XML和JSON绑定博客上代表我们的JCG合作伙伴 Blaise Doughan的空集合和空集合。
翻译自: https://www.javacodegeeks.com/2012/12/jaxb-representing-null-and-empty-collections.html