在 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));
}
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();
}