简体   繁体   中英

unmarshall to class with generic param

I'm trying to deserialize xml string with library JAXB to specific class.

public class Sandbox {
    public static void main(String[] args) throws JAXBException {
        String xml = "<root><child><base-value>val1</base-value><baseimpl-value>val2</baseimpl-value></child></root>";
        Sandbox.Do(xml, BaseImpl.class);
    }

    public static void Do(String xml, Class c) throws JAXBException{
        JAXBContext jc = JAXBContext.newInstance(Parent.class, c);
        Unmarshaller um = jc.createUnmarshaller();

        Parent<BaseImpl> p = (Parent<BaseImpl>) um.unmarshal(new StringReader(xml));
        System.out.println(p.child);
    }
}

@XmlRootElement(name = "root")
class Parent<T extends Base> {
    @XmlElement
    T child;
}

abstract class Base {
    @XmlElement(name = "base-value")
    String BaseValue;
}

@XmlRootElement
class BaseImpl extends Base {
    @XmlElement(name = "baseimpl-value")
    String BaseImplValue;

    @Override
    public String toString(){
        return super.BaseValue + ", " + this.BaseImplValue;
    }
}

JAXB is trying to initiliaze Base interface, what fail with exception Unable to create an instance of sandbox.Base... event though class name is passed to JAXBContext.newInstance function.

I spent another few hours cursing over Jaxb and finally found solution for my problem. The thing, which is missing is param name in annotation at @XmlRootElement(name = "child") . That's all I needed, everything works just fine.

Hope someone will find this helpful and save his time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM