注意: 我是EclipseLink JAXB (MOXy)负责人,也是JAXB (JSR-222)专家组的成员。
MOXy 提供基于 JAXB 注释的 JSON 绑定以及允许您将备用映射应用到域模型的外部绑定文档。我将在下面用一个例子来演示。
作为 JAXB 注释的元数据
下面是一个带有标准 JAXB 注释的简单 Java 模型映射。
package forum10761762;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {
int id;
@XmlElement(name="first-name")
String firstName;
@XmlElement(name="last-name")
String lastName;
}
备用元数据 #1 (alternate1.xml)
在这里,我们将使用 XML 映射文档来取消映射几个字段@XmlTransient
。
<?xml version="1.0"?>
<xml-bindings
xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
package-name="forum10761762">
<java-types>
<java-type name="Customer">
<java-attributes>
<xml-transient java-attribute="id"/>
<xml-transient java-attribute="firstName"/>
</java-attributes>
</java-type>
</java-types>
</xml-bindings>
备用元数据 #2 (alternate2.xml)
在这里,我们将使用 MOXy 的基于路径的映射扩展将 Java 模型映射到不同的 JSON 结构。
<?xml version="1.0"?>
<xml-bindings
xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
package-name="forum10761762">
<java-types>
<java-type name="Customer">
<java-attributes>
<xml-element java-attribute="firstName" xml-path="personalInfo/firstName/text()"/>
<xml-element java-attribute="lastName" xml-path="personalInfo/lastName/text()"/>
</java-attributes>
</java-type>
</java-types>
</xml-bindings>
演示代码
package forum10761762;
import java.util.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextProperties;
public class Demo {
public static void main(String[] args) throws Exception {
Customer customer = new Customer();
customer.id = 123;
customer.firstName = "Jane";
customer.lastName = "Doe";
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
// Output #1
JAXBContext jc1 = JAXBContext.newInstance(new Class[] {Customer.class}, properties);
marshal(jc1, customer);
// Output #2
properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, "forum10761762/alternate1.xml");
JAXBContext jc2 = JAXBContext.newInstance(new Class[] {Customer.class}, properties);
marshal (jc2, customer);
// Output #2
properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, "forum10761762/alternate2.xml");
JAXBContext jc3 = JAXBContext.newInstance(new Class[] {Customer.class}, properties);
marshal(jc3, customer);
}
private static void marshal(JAXBContext jc, Object object) throws Exception {
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(object, System.out);
System.out.println();
}
}
输出
下面是运行演示代码的输出。请注意,从同一对象模型生成了 3 个不同的 JSON 文档。
{
"id" : 123,
"first-name" : "Jane",
"last-name" : "Doe"
}
{
"last-name" : "Doe"
}
{
"id" : 123,
"personalInfo" : {
"firstName" : "Jane",
"lastName" : "Doe"
}
}
欲了解更多信息(来自我的博客)