Generators jaxb marshaller ang (2)

types exist:

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 try to marshal this, I get an error message:

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?

thank

+3
source share
1 answer

How is your JAXBContext created? You will need to make sure he knows about B.class. You might need 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>
+1
source

Source: https://habr.com/ru/post/1761733/


All Articles