Jaxb marshaller ang generics(2)

时间:2010-08-26 14:10:33

标签: spring generics jaxb marshalling

有类型:

class A{}

@XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
@XmlType(propOrder = {"obj"})
@XmlRootElement(name = "response")
public class B<T extends A> extends A{
  private T obj;

  @XmlElement(required = true)
  public T getObj() {
    return obj;
  }
}

当我试图编组时,我得到一个错误:

org.springframework.oxm.MarshallingFailureException: JAXB marshalling exception; nested exception is javax.xml.bind.MarshalException
 - with linked exception:
[com.sun.istack.internal.SAXException2: unable to marshal type "com.my.B" as an element because it is missing an @XmlRootElement annotation]

jaxbMarshaller是否支持通用? 有什么想法吗?

感谢

1 个答案:

答案 0 :(得分:1)

您的JAXBContext是如何创建的?您需要确保它知道B.class。您可能需要使用@XmlSeeAlso注释。

鉴于以下内容:

public class A {

}

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
@XmlType(propOrder = {"obj"})
@XmlRootElement(name = "response")
public class B<T extends A> extends A {

  private T obj;

  @XmlElement(required = true)  
  public T getObj() {  
    return obj;  
  }

  public void setObj(T obj) {
      this.obj = obj;
  }

}

当我跑步时:

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(B.class);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        B b = new B();
        b.setObj(new A());
        marshaller.marshal(b, System.out);

    }

}

我明白了:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<response>
    <obj/>
</response>

当我跑步时:

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(B.class);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        B b = new B();
        b.setObj(new B());
        marshaller.marshal(b, System.out);

    }

}

我明白了:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<response>
    <obj xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="b"/>
</response>
相关问题