JAXB MOXy 2.4.1属性重载不起作用

时间:2013-01-30 17:11:02

标签: java jaxb eclipselink moxy

我有两个继承的类(ClassTop - > ClassChild),每个类都有一个数据类,每个类都有继承的属性(ClassTopData - > ClassChildData) :

ClassTop:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="root")
public class ClassTop {

    @XmlElement(name="title")
    private String title = null;

    @XmlElement(name="meta")
    private ClassTopData meta = new ClassTopData();

    public String getTitle() {return title;}
    public void setTitle(String title) {this.title = title;}

    public ClassTopData getMeta() {return meta;}
    public void setMeta(ClassTopData meta) {this.meta = meta;}

}

ClassChild扩展ClassTop: 重要提示:ClassChild也包含 property meta ,但有ClassTopData的继承变体:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="news")
public class ClassChild extends ClassTop {

    @XmlElement(name="childName")
    private String childName = null;

    @XmlElement(name="meta") // same property name...
    private ClassChildData meta = new ClassChildData(); //... but subclassed data 

    public String getChildName() {return childName;}
    public void setChildName(String childName) {this.childName = childName;}

    public ClassChildData getMeta() {return meta;}
    public void setMeta(ClassChildData meta) {this.meta = meta;}
}

两个数据类:

ClassTopData

@XmlAccessorType(XmlAccessType.FIELD)
public class ClassTopData {

    private String data1 = null;
    private String data2 = null;

    public String getData1() {return data1;}
    public void setData1(String data1) {this.data1 = data1;}

    public String getData2() {return data2;}
    public void setData2(String data2) {this.data2 = data2;}

}

ClassChildData

@XmlAccessorType(XmlAccessType.FIELD)
public class ClassChildData extends ClassTopData {

    private String data3 = null;

    public String getData3() {return data3;}
    public void setData3(String data3) {this.data3 = data3;}

}

当我封送ClassChild并将其读回时,data3为null:

    ClassChild a = new ClassChild();
    a.setTitle("title");
    a.getMeta().setData1("1");
    a.getMeta().setData2("2");
    a.getMeta().setData3("3");


    // Write:
    JAXBContext context = JAXBContext.newInstance(ClassChild.class);
    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
    ... get some OutputStream os ...
    m.marshal(a, os);

    // Read back:
    JAXBContext jc = JAXBContext.newInstance(ClassChild.class);
    Unmarshaller u = jc.createUnmarshaller();
    ... get the InputStream is ...
    ClassChild r = (ClassChild)(u.unmarshal(is));
    System.out.println("data3: "+r.getMeta().getData3());

输出

data3: null

XML看起来像这样:

<?xml version="1.0" encoding="UTF-8"?>
<news>
   <title>title</z:title>
   <meta>
      <data1>1</data1>
      <data2>2</data2>
      <data3>3</data3>
   </meta>
</news>

0 个答案:

没有答案