将自定义异常序列化为JSON,并非所有字段都是序列化的

时间:2013-09-27 15:05:36

标签: java json serialization jackson custom-exceptions

我正在尝试使用Jackson库中的writeValueAsString()方法在Java中序列化自定义Exception。我打算通过HTTP将它发送到另一台机器。这是部分工作,因为序列化后并非所有字段都包含在JSON中。顶级异常Throwable实现Serializable接口,还有一些构造函数可以添加有关要序列化的信息。我想真相就在这里。请帮忙提一些建议。这是我的自定义异常代码:

import java.io.Serializable;

public class MyException extends RuntimeException{

private static String type = null;
private static String severity = null;

// somewhere on google I red that should use setters to make serialize work

public static void setType(String type) {
    MyException.type = type;
}

public static void setSeverity(String severity) {
    MyException.severity = severity;
}

public MyException(String message) {
    super(message);
}
}

我使用的代码中的某处:

MyException exc = new MyException("Here goes my exception.");
MyException.setType(exc.getClass().getSimpleName());    
MyException.setSeverity("Major");
throw exc;

在其他地方我有:

ObjectMapper mapper = new ObjectMapper();
try {   
     responseBuilder.entity(mapper.writeValueAsString(MyException) );
} 
catch (JsonGenerationException e) {e.printStackTrace(); } 
catch (JsonMappingException e) {e.printStackTrace(); } 
catch (IOException e) { e.printStackTrace(); }

结果JSON对象是:

{"cause":null,"message":"Here goes my exception.","localizedMessage":"Here goes my exception.","stackTrace":[{...a usual stack trace...}]}

在这里,我还希望看到我的类型和严重性字段。

1 个答案:

答案 0 :(得分:4)

我使typeseverity非静态,似乎工作正常。我使用了以下代码,并且在序列化输出中看到了typeseverity

public class MyException extends RuntimeException
{
    private String type = null;
    private String severity = null;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getSeverity() {
        return severity;
    }

    public void setSeverity(String severity) {
        this.severity = severity;
    }

    public MyException(String message) {
        super(message);
    }
}

...和

MyException exc = new MyException("Here goes my exception.");
exc.setType(exc.getClass().getSimpleName());    
exc.setSeverity("Major");

ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(exc));

希望这有帮助!