如何序列化Exception的子类?
这是我的例外:
@XmlType
public static class ValidationFault extends Exception {
public ValidationFault() {
}
}
我尝试过使用@XmlTransient和@XmlAccessorType的各种变体,但是JAXB不断尝试序列化getStackTrace / setStackTrace对,这是无法完成的。
如何告诉JAXB忽略父级的所有字段?
答案 0 :(得分:3)
我用以下信息解决了这个问题: http://forums.java.net/jive/thread.jspa?messageID=256122
您需要使用以下配置初始化JAXBContext(其中jaxbObj是要序列化的对象):
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);
答案 1 :(得分:2)
您可以使用XmlAdapter自行处理编组/解组。像这样:
@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);
}
}