4

如何序列化 Exception 的子类?

这是我的例外:

@XmlType
public static class ValidationFault extends Exception {
    public ValidationFault() {

    }
}

我已经尝试过使用@XmlTransient 和@XmlAccessorType 的各种变体,但是JAXB 不断尝试序列化getStackTrace/setStackTrace 对,这是无法完成的。

如何告诉 JAXB 忽略父项上的所有字段?

4

2 回答 2

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);
于 2009-08-12T22:29:10.890 回答
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);
  }
}
于 2009-08-06T21:50:48.363 回答