我对JAXB很新,我在尝试解组通用对象时遇到了麻烦。问题是我需要能够编组和解组任何对象(java.lang.Object)。我成功地完成了元帅,但是当我运行unmarshal时,我在响应中得到一个“ElementNSImpl”对象,而不是我自己的对象。
这是涉及的豆类:
的 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.index 的内容:
Message
SomeBean
生成的xml很好(<?xml version="1.0" encoding="UTF-8" standalone="yes"?><message><somebean><variable>lalallalala</variable></somebean></message>
)但是当我在unmarshal之后评估“msg.getObj()”时,我没有得到SomeBean实例,而是一个ElementNSImpl。
所以,我的问题是,如何找回我已经编组的SomeBean对象?
提前致谢。
答案 0 :(得分:0)
最后用这个答案解决了它:https://stackoverflow.com/a/9081855/1060779,我应用了两次unmarshaling:
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());
}