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

lex*_*exx 3 java serialization json custom-exceptions jackson

我正在尝试使用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);
}
}
Run Code Online (Sandbox Code Playgroud)

我在代码中使用的某处:

MyException exc = new MyException("Here goes my exception.");
MyException.setType(exc.getClass().getSimpleName());    
MyException.setSeverity("Major");
throw exc;
Run Code Online (Sandbox Code Playgroud)

在其他地方,我有:

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(); }
Run Code Online (Sandbox Code Playgroud)

结果JSON对象为:

{"cause":null,"message":"Here goes my exception.","localizedMessage":"Here goes my exception.","stackTrace":[{...a usual stack trace...}]}
Run Code Online (Sandbox Code Playgroud)

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

Jac*_*all 5

我提出typeseverity非静态的,它似乎是工作的罚款。我使用了以下代码,type并且severity在序列化的输出中看到了两者。

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

...和

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));
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!

  • 类的静态成员与该类相关联,而不与该类的任何实例关联;因此,它们将不会序列化。这个问题可以提供更多的背景信息:http://stackoverflow.com/questions/1008023/how-to-serialize-static-data-members-of-a-java-class。 (2认同)