How do you serialize an Exception subclass in JAXB

2019-02-18 03:40发布

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?

标签: java jaxb
2条回答
放荡不羁爱自由
2楼-- · 2019-02-18 04:16

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);
查看更多
我想做一个坏孩纸
3楼-- · 2019-02-18 04:35

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);
  }
}
查看更多
登录 后发表回答