JaxB marshalling wildcard generics extended class



I am facing an issue while marshalling a java class.


In code snippet 1, Class A use List<B> whereas snippet 2 has List<B<? extends C>>.


Code snippet 1 produces <?xml version="1.0" encoding="UTF-8" standalone="yes"?><a><test><item><name>Success!!</name></item></test></a>


whereas snippet 2 is missing data inside Class C <?xml version="1.0" encoding="UTF-8" standalone="yes"?><a><test/></a>


Can someone please help me resolve this?


Snippet 1:



public class JaxBXMLTest {
@Test
public void testMarshalling() throws JAXBException{
testBaseClass();
}

private void testBaseClass() throws JAXBException{
A resp = new A();
C test = new C();
test.setName("Success!!");
List<B> data = new ArrayList<B>();
B wrap = new B();
wrap.setItem(test);
data.add(wrap);
resp.setTest(data);

JAXBContext context = JAXBContext.newInstance(A.class);
Marshaller m = context.createMarshaller();
//for pretty-print XML in JAXB

// Write to System.out for debugging
m.marshal(resp, System.out);
}

@XmlRootElement
@XmlType(name = "MyResponse")
public static class A{
List<B> test;

public List<B> getTest() {
return test;
}

public void setTest(List<B> test) {
this.test = test;
}

}

public static class B{
private C item;

public C getItem() {
return item;
}

public void setItem(C item) {
this.item = item;
}
}
public static class C{
private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}


}


Snippet 2:



public class JaxBXMLTestB {
@Test
public void testMarshalling() throws JAXBException {
testSubClass();
}

private void testSubClass() throws JAXBException {
A resp = new A();
C test = new C();
test.setName("Failure!!!");

B<? extends C> wrap = new B<C>();
wrap.setItem(test);

List<B<? extends C>> finalObj = new ArrayList<B<? extends C>>();
finalObj.add(wrap);
resp.setTest(finalObj);

JAXBContext context = JAXBContext.newInstance(A.class);
Marshaller m = context.createMarshaller();
// for pretty-print XML in JAXB
// m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

// Write to System.out for debugging
m.marshal(resp, System.out);
}

@XmlRootElement
@XmlType(name = "MySubClassResponse")
public static class A {
List<B<? extends C>> test;

public A(){
test = new ArrayList<B<? extends C>>();
}

public List<B<? extends C>> getTest() {
return test;
}

public void setTest(List<B<? extends C>> test) {
this.test = test;
}
}

public static class B<T extends C> {
private T item;

public T getItem() {
return item;
}

public void setItem(C item) {
this.item = (T) item;
}
}

public static class C {
private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}


}


No comments:

Post a Comment