安康网站建设电话,上海快速优化排名,工信部网站备案电话,化妆品购物网站建设目的示范代码 以下演示代码将用于Java模型的所有不同版本。 它只是将一个集合设置为null#xff0c;第二个设置为空列表#xff0c;第三个设置为填充列表。 package package blog.xmlelementwrapper;import java.util.ArrayList;
import javax.xml.bind.*;public class Demo {pu… 示范代码 以下演示代码将用于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 ArrayListString();root.populatedCollection new ArrayListString();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 {ListString nullCollection;ListString emptyCollection;ListString populatedCollection;} 检查输出我们看到对应于nullCollection和emptyCollection字段的输出是相同的。 这意味着使用默认映射我们无法往返实例。 对于非编组用例 nullCollection和EmptyCollection的值将是该类将其初始化为的字段的值在这种情况下为null。 ?xml version1.0 encodingUTF-8?
rootpopulatedCollectionfoo/populatedCollectionpopulatedCollectionbar/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 {XmlElementWrapperListString nullCollection;XmlElementWrapperListString emptyCollection;XmlElementWrapperListString populatedCollection;} 空集合的表示形式保持不变但XML文档中不存在。 对于空集合我们看到仅分组元素被整理。 由于null和empty的表示形式不同因此我们可以往返使用该用例。 ?xml version1.0 encodingUTF-8?
rootemptyCollection/populatedCollectionpopulatedCollectionfoo/populatedCollectionpopulatedCollectionbar/populatedCollection/populatedCollection
/root映射3 – XmlElementWrappernillable 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(nillabletrue)ListString nullCollection;XmlElementWrapper(nillabletrue)ListString emptyCollection;XmlElementWrapper(nillabletrue)ListString populatedCollection;} 现在所有三个字段都存在分组元素。 xsinil属性用于指示nullCollection字段为null。 像以前的映射一样此映射可以往返。 ?xml version1.0 encodingUTF-8?
rootnullCollection xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:niltrue/emptyCollection/populatedCollectionpopulatedCollectionfoo/populatedCollectionpopulatedCollectionbar/populatedCollection/populatedCollection
/root 参考 JAXB –在Java XML和JSON绑定博客上代表我们的JCG合作伙伴 Blaise Doughan的空集合和空集合。 翻译自: https://www.javacodegeeks.com/2012/12/jaxb-representing-null-and-empty-collections.html