当集合为空时,在JAXB中省略包装器标签

时间:2017-06-01 14:15:10

标签: java xml jaxb

在JAXB中,您可以使用@XmlElementWrapper属性指定用于包装元素集合的标记。但是,即使集合为空,也会显示这些包装器标记(如果集合为null,则不会显示这些标记)。如果集合为空,有没有办法让JAXB省略包装器标签?在集合上使用适配器似乎不起作用,因为JAXB解释这意味着它应该将适配器应用于集合中的每个元素。

2 个答案:

答案 0 :(得分:4)

您可以通过使用以某种程度上的hackish强制执行您想要的行为 Marshal Event Callbacks

@XmlRootElement(name="example")
@XmlAccessorType(XmlAccessType.FIELD)
public class Example {

    @XmlElementWrapper(name="wrapper")
    @XmlElement(name="item")
    private List<Item> items;

    // invoked by Marshaller before marshalling
    private void beforeMarshal(Marshaller marshaller) {
         if (items != null && items.isEmpty())
            items = null;
    }

    // ... getters and setters
}

Marshal Event Callbacks中所述 实际上有两种替代方法可以使用marshal回调:

  1. beforeMarshal和/或afterMarshal方法直接放入您的班级,就是这样。 (这是更简单的方法,这就是我在答案中使用它的原因。)
  2. 创建Marshaller.Listener并在其中编写beforeMarshalafterMarshal方法。然后,您需要在Marshaller
  3. 中注册此监听器

答案 1 :(得分:1)

您可以使用Marshaller

的侦听器机制

您可以添加/设置如下所示的监听器:

jaxbMarshaller.setListener( new Listener()
{
    @Override
    public void beforeMarshal(Object source) 
    {
        if ( source instanceof MyCollectionWrapper )
        {
            MyCollectionWrapper wrapper = (MyCollectionWrapper)source;
            if ( wrapper.getCollection() != null && wrapper.getCollection().isEmpty() )
            {
                wrapper.setCollection( null );
            }
        }

    }
});

其中MyCollectionWrapper是表示包装类的类。

这应该在集合为空时删除包装器标记。

相关问题