我想为现有的JavaScript库(SmartClient)构建一个REST java后端(使用jersey)。这个JavaScript库以不同的格式将请求发送到我的服务器。
如何将XML反序列化为包含不同类型内容的容器对象?
这是一个例子,我已经尝试过:
import java.io.StringReader;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Box {
static class Ball {
public String size;
public String toString() {return "Ball(" + size + ")";}
}
static class Cat {
public String name;
public String toString() {return "Cat(" + name + ")";}
}
public static void main(String[] args) throws Exception {
printContent("<box><content><size>3</size></content></box>");
printContent("<box><content><name>Mimi</name></content></box>");
}
private static void printContent(String xml) throws JAXBException {
JAXBContext context = JAXBContext.newInstance(Box.class, Ball.class, Cat.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
Box box = (Box) unmarshaller.unmarshal(new StringReader(xml));
System.out.println(box.content);
}
// not working
public Object content;
// not working
// @XmlMixed
// public Object content;
// not working
// @XmlAnyElement
// public List<Object> content;
// not working
// @XmlAnyElement(lax=true)
// public List<Object> content;
// not working
// @XmlJavaTypeAdapter(ContentXmlAdapter.class)
// public Object content;
// static class ContentXmlAdapter extends XmlAdapter<String, Object>{
//
// @Override
// public Object unmarshal(String v) throws Exception {
// System.out.println("unmarshal("+v+")");
// return null;
// }
//
// public String marshal(Object v) throws Exception {throw new UnsupportedOperationException();}
// }
}