我有一个包装类,其属性类型是多个子类的超类。我想编组JSON并为该字段编组子类。当我这样做时,我得到错误:
java.lang.IllegalStateException:无效的JSON名称空间:http://www.w3.org/2001/XMLSchema-instance
具体来说,我有一个“包装”类,其中包含类型为SuperClass的“result”字段,但它始终是某个子类的实例(下面的“SubClass”)。如果我使我的Wrapper类将其“result”字段定义为子类类型“SubClass”,它可以正常工作,但是当它是“SuperClass”类型但是SubClass的实例时会收到错误。
我可以在这里使用注释吗?我是否必须做某种定制编组?
public class JsonText {
@XmlRootElement
public static class SuperClass {
}
@XmlRootElement
public static class SubClass extends SuperClass {
private int val;
public int getVal() {return val; }
public void setVal(int i) {
val = i;
}
}
@XmlRootElement
public static class ErrorMessage {
private String msg;
public String getMsg() { return msg; }
public void setMsg(String s) { msg = s;}
}
@XmlRootElement
public static class Wrapper {
private SuperClass result;
private ErrorMessage error;
public SuperClass getResult() { return result; }
public void setResult(SuperClass sc) { result = sc; }
public ErrorMessage getError() { return error; }
public void setError(ErrorMessage e) { error = e; }
}
public static void main(String[] args) throws Exception{
ErrorMessage err = new ErrorMessage();
err.setMsg("my error");
SubClass sc = new SubClass();
sc.setVal(1);
Wrapper wrapper = new Wrapper();
wrapper.setResult(sc);
wrapper.setError(err);
JAXBContext jc = JAXBContext.newInstance(SuperClass.class, SubClass.class, Wrapper.class);
Configuration config = new Configuration();
MappedNamespaceConvention con = new MappedNamespaceConvention config);
StringWriter writer = new StringWriter();
XMLStreamWriter xmlStreamWriter = new MappedXMLStreamWriter(con, writer);
Marshaller marshaller = jc.createMarshaller();
marshaller.marshal(wrapper, xmlStreamWriter);
System.out.println(writer.toString());
}
}