简体   繁体   English

取消编组通用参数类

[英]unmarshall to class with generic param

I'm trying to deserialize xml string with library JAXB to specific class. 我正在尝试使用库JAXB将xml字符串反序列化为特定的类。

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. JAXB正在尝试初始化Base接口,该操作失败,但发生异常Unable to create an instance of sandbox.Base...尽管将类名传递给JAXBContext.newInstance函数,但Unable to create an instance of sandbox.Base...事件。

I spent another few hours cursing over Jaxb and finally found solution for my problem. 我花了几个小时骂Jaxb,终于找到了解决我问题的方法。 The thing, which is missing is param name in annotation at @XmlRootElement(name = "child") . 缺少的是@XmlRootElement(name = "child")注释中的参数name That's all I needed, everything works just fine. 这就是我所需要的,一切都很好。

Hope someone will find this helpful and save his time. 希望有人会对此有所帮助并节省时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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