注意: 我是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" : [ {
}, {
} ]
}
了解更多信息