maxivis
maxivis

Reputation: 1787

JAXB Unmarshal generic object

I'm pretty new to JAXB and I'm having trouble trying to unmarshal a generic object. The thing is that I need to be able to marshal and unmarshal any object (java.lang.Object). I did the marshal successfully, but when I run the unmarshal I'm getting an "ElementNSImpl" object in the response, instead of my own object.
This are the involved beans:
Message.java

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Message {
    @XmlAnyElement(lax=true)
    private Object obj;
    //getter and setter
}


SomeBean.java

@XmlRootElement(name="somebean")
public class SomeBean {
    private String variable;
    //getter and setter
}

And this is the code to marshal/unmarshal

Message m = new Message();
SomeBean sb = new SomeBean();
sb.setVariable("lalallalala");
m.setObj(sb);

JAXBContext jaxbContext = JAXBContext.newInstance("jaxb.entities");
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
StringWriter sw = new StringWriter();
jaxbMarshaller.marshal(m, sw);
System.out.println(sw.toString());  //this shows me the xml correctly

//unmarshal code
JAXBContext jc = JAXBContext.newInstance(Message.class);
StringReader reader = new StringReader(sw.toString());
Unmarshaller unmarshaller = jc.createUnmarshaller();
Object result = unmarshaller.unmarshal(reader);
Message msg = (Message)result;


Content of jaxb.index:

Message
SomeBean

The generated xml is fine (<?xml version="1.0" encoding="UTF-8" standalone="yes"?><message><somebean><variable>lalallalala</variable></somebean></message>) but when I evaluate "msg.getObj()" after unmarshal I don't get a SomeBean instance, but a ElementNSImpl.
So, my question is, how can I get back the SomeBean object that I've marshaled?
Thanks in advance.

Upvotes: 0

Views: 3276

Answers (1)

maxivis
maxivis

Reputation: 1787

Finally solved it with this answer: https://stackoverflow.com/a/9081855/1060779, I applied twice the unmarshaling:

    Unmarshaller unmarshaller = jc.createUnmarshaller();
    Object result = unmarshaller.unmarshal(reader);
    Message msg = (Message)result;
    if (msg.getObj() instanceof Node) {
        ElementNSImpl e = (ElementNSImpl)msg.getObj();
        Class<?> clazz = Class.forName(packageName.concat(".").concat(e.getNodeName()));
        jc = JAXBContext.newInstance(clazz);
        unmarshaller = jc.createUnmarshaller();
        SomeBean sBean = (SomeBean)unmarshaller.unmarshal((ElementNSImpl)msg.getObj());
        System.out.println(sBean.toString());
    }

Upvotes: 0

Related Questions