我的类中有一个集合,它使用 @XmlElementWrapper 将集合包装在额外的元素中。
所以,我的类(class)看起来像这样:
class A {
@XmlElement(name = "bee")
@XmlElementWrapper
public List<B> bees;
}
我的 XML 看起来像这样:
<a>
<bees>
<bee>...</bee>
<bee>...</bee>
</bees>
</a>
太好了,这就是我想要的。然而,当我尝试编码为 JSON 时,我得到了这个:
{
"bees": {
"bee": [
....
]
}
}
而且我不想要那个额外的“蜜蜂” key 。
在进行此编码时是否可以以某种方式让 MOXy 忽略 XmlElement 部分?因为我仍然需要名称是“bees”而不是“bee”,而且我两个都不想要。
我正在使用 MOXy 2.4.1 和 javax.persistence 2.0.0。
最佳答案
注意:我是EclipseLink JAXB (MOXy) JAXB (JSR-222) 的领导者和成员专家组。
oxm.xml
您可以使用 MOXy 的外部映射文档为 JSON 绑定(bind)提供备用映射(请参阅: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 的外部映射文件来覆盖 A
类上的 bees
属性的映射。
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" : [ {
}, {
} ]
}
了解更多信息
关于jaxb - 使用 XmlElementWrapper 时编码集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14002508/