views:

33

answers:

1

there are types:

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;
  }
}

When i'm trying to marshal this i get an error:

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]

Does jaxbMarshaller work with generic? Any ideas?

thanks

+1  A: 

How is your JAXBContext getting created? You will need to ensure that it is aware of B.class. You may need to use the @XmlSeeAlso annotation.

Given the following:

public class A {

}

and:

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;
  }

}

When I run:

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);

    }

}

I get:

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

And when I run:

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);

    }

}

I get:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<response>
    <obj xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="b"/>
</response>
Blaise Doughan
i'm trying to marshal instance of the following class:public class B<C> extends A{...}WHERE C is sub class of A
roman
I have updated my answer, it may be related to how your JAXBContext is getting created.
Blaise Doughan