2016-11-17 5 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.index
내용 :

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

마지막이 답변으로 해결 :

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()); 
    } 
: https://stackoverflow.com/a/9081855/1060779, 나는 두 번 비 정렬 화를 적용
관련 문제