2016-11-17 70 views
0

我對JAXB來說很新,而且在嘗試解組通用對象時遇到了問題。問題是我需要能夠編組和解組任何對象(java.lang.Object)。我成功地完成了元帥,但是當我運行解組時,我在響應中獲得了一個「ElementNSImpl」對象,而不是我自己的對象。
這是涉及豆:
Message.javaJAXB Unmarshal通用對象

@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對象?
在此先感謝。

回答

0

最後這個答案解決它: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()); 
    }