JAXB Marshal Field that is a subclass
I have a wrapper class with a property whose type is a superclass of several subclasses. I want to marshal to JSON and have the subclass marshalled for that field. When I do it, I get error:
java.lang.IllegalStateException: Invalid JSON namespace: http://www.w3.org/2001/XMLSchema-instance
Specifically, I have a "Wrapper" class with a "result" field of type SuperClass but it will always be an instance of some sub class ("SubClass" below). If I make my Wrapper class have its "result" field defined as subclass type "SubClass" it works OK, but when it is of type "SuperClass" but the instance of of SubClass I get the error.开发者_开发百科
Is there an annotation that I can use here? Do I have to do some sort of custom marshaller?
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());
}
}
精彩评论