簡體   English   中英

JAXB Unmarshal通用對象

[英]JAXB Unmarshal generic object

我對JAXB相當陌生,嘗試解組通用對象時遇到麻煩。 問題是我需要能夠封送和取消封送任何對象(java.lang.Object)。 我成功地完成了編組,但是當我執行解組時,響應中得到的是“ ElementNSImpl”對象,而不是我自己的對象。
這是涉及的bean:
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
}

這是要編組/解組的代碼

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;


jaxb.in​​dex的內容:

Message
SomeBean

生成的xml很好( <?xml version="1.0" encoding="UTF-8" standalone="yes"?><message><somebean><variable>lalallalala</variable></somebean></message> ),但在解組后評估“ msg.getObj()”時,我沒有得到SomeBean實例,而是ElementNSImpl。
所以,我的問題是,如何找回已封送的SomeBean對象?
提前致謝。

最終用以下答案解決了它: https : //stackoverflow.com/a/9081855/1060779 ,我應用了兩次解組:

    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());
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM