所以我有课名:
class Name {
private String first;
private String middle;
private String last;
public getFirst() { return first; }
public getMiddle() { return middle; }
public getLast() { return last; }
}
我想使用映射XML序列化此类的实例,而不必在映射XML中列出每个属性:
<java-types>
<java-type name="Name">
<java-attributes>
<xml-element java-attribute="first"/>
<xml-element java-attribute="middle"/>
<xml-element java-attribute="last"/>
</java-attributes>
</java-type>
</java-types>
理想情况下,我希望有这样的映射文件:
<java-types>
<java-type name="Name" xml-accessor-type="GETTERS"/>
</java-types>
我有一些像这样的传统DTO类,仅用于序列化(没有有意图的setter),有30个或更多属性,理想情况下我想避免在映射文件中列出每个属性。
答案 0 :(得分:0)
注意:我是EclipseLink JAXB (MOXy)主管,是JAXB 2 (JSR-222)专家组的成员。
对于这个用例,我建议使用字段访问类型。指定此项时,JAXB实现将使用字段(实例变量)来访问数据,而不是通过属性(get方法)。下面我将演示如何使用MOXy的外部映射文档扩展:
<强> bindings.xml 强>
<?xml version="1.0"?>
<xml-bindings
xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
package-name="forum10141543">
<java-types>
<java-type name="Name" xml-accessor-type="FIELD">
<xml-root-element/>
</java-type>
</java-types>
</xml-bindings>
命名强>
package forum10141543;
class Name {
private String first;
private String middle;
private String last;
public Name() {
}
public Name(String first, String middle, String last) {
this.first = first;
this.middle = middle;
this.last = last;
}
public String getFirst() { return first; }
public String getMiddle() { return middle; }
public String getLast() { return last; }
}
<强> jaxb.properties 强>
要将MOXy指定为JAXB提供程序,您需要在与域类相同的程序包中添加名为jaxb.properties
的文件,并使用以下条目。
javax.xml.bind.context.factory = org.eclipse.persistence.jaxb.JAXBContextFactory
<强>演示强>
以下代码演示了在引导JAXBContext
时如何传入绑定文件:
package forum10141543;
import java.util.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextFactory;
public class Demo {
public static void main(String[] args) throws Exception {
Map<String, Object> properties = new HashMap<String, Object>(1);
properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, "forum10141543/bindings.xml");
JAXBContext jc = JAXBContext.newInstance(new Class[] {Name.class}, properties);
Name name = new Name("Jane", "Anne", "Doe");
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(name, System.out);
}
}
<强>输出强>
<?xml version="1.0" encoding="UTF-8"?>
<name>
<first>Jane</first>
<middle>Anne</middle>
<last>Doe</last>
</name>
了解更多信息