在 Java 7 中,是否可以将 Exception
对象转换为 Json?
例子:
try {
//something
} catch(Exception ex) {
Gson gson = new Gson();
System.out.println(gson.toJson(ex));
}
最佳答案
好吧,虽然您不想转换异常对象本身,而是转换其中包含的消息,但可以使用您设计的格式,例如:
// […]
} catch (Exception ex) {
Gson gson = new Gson();
Map<String, String> exc_map = new HashMap<String, String>();
exc_map.put("message", ex.toString());
exc_map.put("stacktrace", getStackTrace(ex));
System.out.println(gson.toJson(exc_map));
}
根据建议定义 getStackTrace()
that answer :
public static String getStackTrace(final Throwable throwable) {
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw, true);
throwable.printStackTrace(pw);
return sw.getBuffer().toString();
}
关于java - 将异常转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22271099/