我使用MOXY作为编组/解组的JAXB实现。
我有一个类List
作为成员变量之一:
public class Model {
@XmlElement(required = true)
protected String time;
@XmlList
protected List<String> labels;
}
我想在编组之后将xml转换为:
<time>25042015</time>
<lbl>label1 label2 label3</lbl>
所以我想将label
修改为lbl
,如果有空列表,我不希望它显示在XML中。
这是一个遗留类,所以我不是在编辑我的POJO,而是提供了一个extrernal元数据文件:
<java-type name="Modal">
<java-attributes>
<xml-element java-attribute="labels" name="lbl" >
</xml-element>
</java-attributes>
</java-type>
但是有了这个,xml就形成了:
<time>25042015</time>
<lbl>label1</lbl>
<lbl>label2</label>
<lbl>label3</lbl>
所以我在metatdata文件中添加了xml-list="true"
:
<xml-element java-attribute="labels" name="lbl" xml-list="true"></xml-element>
这解决了我制作XML的问题:<lbl>label1 label2 label3</lbl>
但如果我的列表为空:labels = new ArrayList()
,
向XML添加一个我不想要的空列表。类似的东西:
<time>25042015</time>
<lbl></lbl>
如果没有xml-list="true"
,则不会出现空列表。
如何从XML中删除空列表?
我尝试添加XmlAdpater
,这样如果列表为空,则将其设为null(因此它不会出现在XML中):
public class ListAdapter extends XmlAdapter<List, List>{
@Override
public List unmarshal(List v) throws Exception {
System.out.println("********Inside ListAdapter UNMARSHALL********");
return v;
}
@Override
public List marshal(List v) throws Exception {
System.out.println("********Inside ListAdapter MARSHALL********");
if(v != null && v.isEmpty())
return null;
return v;
}
}
但是这给出了一个例外:
12:49:18,893 ERROR [stderr] (default task-1) javax.xml.bind.JAXBException:
12:49:18,893 ERROR [stderr] (default task-1) Exception Description: XmlList is only allowed on a collection or array property but [labels] is not a collection or array property.
12:49:18,893 ERROR [stderr] (default task-1) - with linked exception:
12:49:18,893 ERROR [stderr] (default task-1) [Exception [EclipseLink-50018] (Eclipse Persistence Services - 2.6.1.v20150916-55dc7c3): org.eclipse.persistence.exceptions.JAXBException