我正在使用 Gson 在我的应用程序中生成调试输出
Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
gson.toJson(myObject);
但 Gson 在尝试序列化数据结构时确实会提示循环引用错误。 这可以用 Jackson 库来完成吗?
UPD Gson 2.3.1:2014 年 11 月 20 日发布
Added support to serialize objects with self-referential fields. The self-referential field is set to null in JSON. Previous version of Gson threw a StackOverflowException on encountering any self-referential fields.
The most visible impact of this is that Gson can now serialize Throwable (Exception and Error)
最佳答案
使用 Jackson 进行序列化:
public String serialize(Object obj, boolean pretty) {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
if (pretty) {
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
}
return mapper.writeValueAsString(obj);
}
关于java - 与 jackson 一起将对象转储到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9767131/