使用XmlElementWrapper时编组集合

时间:2012-12-22 11:38:13

标签: jaxb moxy

我的类上有一个集合,它使用@XmlElementWrapper将集合包装在一个额外的元素中。

所以,我的班级看起来像这样:

class A {
  @XmlElement(name = "bee")
  @XmlElementWrapper
  public List<B> bees;
}

然后我的XML看起来像:

<a>
  <bees>
    <bee>...</bee>
    <bee>...</bee>
  </bees>
</a>

太好了,这就是我想要的。但是,当我尝试编组JSON时,我得到了这个:

{
  "bees": {
    "bee": [
      ....
    ]
  }
}

我不希望那里有额外的“蜜蜂”钥匙。

在进行此编组操作时,是否有可能以某种方式让MOXy忽略XmlElement部分?因为我仍然需要这个名字是“蜜蜂”而不是“蜜蜂”,我不想要两者。

我正在使用MOXy 2.4.1和javax.persistence 2.0.0。

1 个答案:

答案 0 :(得分:2)

注意:我是EclipseLink JAXB (MOXy)主管,是JAXB (JSR-222)专家组的成员。

<强> oxm.xml

您可以使用MOXy的外部映射文档为JSON绑定提供备用映射(请参阅:http://blog.bdoughan.com/2010/12/extending-jaxb-representing-annotations.html)。

<?xml version="1.0"?>
<xml-bindings xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
    package-name="forum14002508">
    <java-types>
        <java-type name="A">
            <java-attributes>
                <xml-element java-attribute="bees" />
            </java-attributes>
        </java-type>
    </java-types>
</xml-bindings>

<强>演示

在下面的演示代码中,我们将创建两个JAXBContext的实例。第一个是仅构建我们将用于XML的JAXB注释。第二个是基于JAXB注释构建的,并使用MOXy的外部映射文件来覆盖bees类上A属性的映射。

package forum14002508;

import java.util.*;
import javax.xml.bind.*;

import org.eclipse.persistence.jaxb.JAXBContextProperties;

public class Demo {

    public static void main(String[] args) throws Exception {

        List<B> bees = new ArrayList<B>();
        bees.add(new B());
        bees.add(new B());
        A a = new A();
        a.bees = bees;

        JAXBContext jc1 = JAXBContext.newInstance(A.class);
        Marshaller marshaller1 = jc1.createMarshaller();
        marshaller1.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller1.marshal(a, System.out);

        Map<String, Object> properties = new HashMap<String, Object>(3);
        properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, "forum14002508/oxm.xml");
        properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
        properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
        JAXBContext jc2 = JAXBContext.newInstance(new Class[] {A.class}, properties);
        Marshaller marshaller2 = jc2.createMarshaller();
        marshaller2.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller2.marshal(a, System.out);
    }

}

<强>输出

以下是运行与您的用例匹配的演示代码的输出。

<a>
   <bees>
      <bee/>
      <bee/>
   </bees>
</a>
{
   "bees" : [ {
   }, {
   } ]
}

了解更多信息

相关问题