How do you serialize a subclass of Exception?
Here is my exception:
@XmlType
public static class ValidationFault extends Exception {
public ValidationFault() {
}
}
I have tried all sorts of variations on using @XmlTransient and @XmlAccessorType, but JAXB continually tries to serialize the getStackTrace/setStackTrace pair, which can't be done.
How do I tell JAXB to ignore all the fields on the parent?
I solved this with the information at:
http://forums.java.net/jive/thread.jspa?messageID=256122
You need to initialize your JAXBContext with the following config (where jaxbObj is the object to serialize):
Map<String, Object> jaxbConfig = new HashMap<String, Object>();
// initialize our custom reader
TransientAnnotationReader reader = new TransientAnnotationReader();
try {
reader.addTransientField(Throwable.class.getDeclaredField("stackTrace"));
reader.addTransientMethod(Throwable.class.getDeclaredMethod("getStackTrace"));
} catch (SecurityException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
}
jaxbConfig.put(JAXBRIContext.ANNOTATION_READER, reader);
JAXBContext jc = JAXBContext.newInstance(new Class[] {jaxbObj.getClass()},jaxbConfig);
You could use an XmlAdapter to handle the marshalling/unmarshalling yourself. Something like this:
@XmlRootElement
public class JaxbWithException {
public ValidationFault fault = new ValidationFault("Foo");
@XmlJavaTypeAdapter(value = ValidationFaultAdapter.class)
public static class ValidationFault extends Exception {
public ValidationFault(String msg) {
super(msg);
}
}
public static class ValidationFaultAdapter extends
XmlAdapter<String, ValidationFault> {
@Override
public String marshal(ValidationFault v) throws Exception {
return v == null ? null : v.getMessage();
}
@Override
public ValidationFault unmarshal(String v) throws Exception {
return v == null ? null : new ValidationFault(v);
}
}
public static void main(String[] args) {
JAXB.marshal(new JaxbWithException(), System.out);
}
}