我有一个可能包含空列表的对象。如果列表为空,我不希望在我的 XML 的 String
输出中看到该标记。
但是,JAXB 仍在输出空标记。
我在类 RemoteEdition.java
中的字段:
@XmlElementWrapper(name = "dealings")
@XmlElement(name = "dealing")
private List<Dealing> dealings;
dealings
为空列表时的期望输出:
<remoteEdition>
</remoteEdition>
实际输出:
<remoteEdition>
<dealings/>
</remoteEdition>
在 Jackson 中,我会用以下方式注释元素:
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private List<Dealing> dealings;
JAXB 中是否有等效项?我在网上找不到任何例子...... 附言我已经试过了 this solution但它不起作用。
最佳答案
实现这一目标的一个选择是利用 beforeMarshal
方法。此空元素仅在列表 dealings
时创建为空但不为空。
因此您可以将字段设置为null
在beforeMarshal
方法当且仅当列表为空。
这是一个独立的例子:
@XmlRootElement
class Root {
@XmlElementWrapper(name = "wrapper")
@XmlElement
private List<Element> element;
void beforeMarshal(Marshaller u) {
if (element != null && element.isEmpty()) {
element = null;
}
}
}
class Element {
}
public static void main(String[] args) throws JAXBException {
JAXBContext context = JAXBContext.newInstance(Root.class);
StringWriter writer = new StringWriter();
Root jaxbElement = new Root();
jaxbElement.element = new ArrayList<JaxbNullElementWrapper.Element>();
context.createMarshaller().marshal(jaxbElement, writer);
System.out.println(writer.toString());
}
输出:<?xml version="1.0" encoding="UTF-8" standalone="yes"?><root/>
关于java - 不要在 JAXB(对象到字符串)中输出空列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59217725/