如何在JAXB中序列化Exception子类? [英] How do you serialize an Exception subclass in JAXB?
问题描述
如何序列化Exception的子类?
How do you serialize a subclass of Exception?
这是我的例外:
@XmlType
public static class ValidationFault extends Exception {
public ValidationFault() {
}
}
我已经尝试过使用@XmlTransient和@XmlAccessorType的各种变体,但JAXB不断尝试序列化getStackTrace / setStackTrace对,这是无法完成的。
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.
如何告诉JAXB忽略父级的所有字段?
How do I tell JAXB to ignore all the fields on the parent?
推荐答案
我用以下信息解决了这个问题:
http://forums.java.net/jive/thread.jspa?messageID=256122
I solved this with the information at: http://forums.java.net/jive/thread.jspa?messageID=256122
您需要使用以下配置初始化JAXBContext(其中jaxbObj是要序列化的对象):
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);
这篇关于如何在JAXB中序列化Exception子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!