将对象转储为与Jackson的字符串 [英] dump object to String with Jackson

查看:79
本文介绍了将对象转储为与Jackson的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Gson在我的应用程序中生成调试输出

I'm using Gson to generate debug ouput in my application

Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
gson.toJson(myObject);

但是在试图序列化数据结构时,Gson会抱怨循环引用错误。
这可以通过Jackson库完成吗?

But Gson does complain about a circular reference error when attempting to serialize a data structure. Can this be done with Jackson library?

UPD
Gson 2.3.1:2014年11月20日发布

UPD Gson 2.3.1: Released Nov 20, 2014

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序列化:

To serialize with Jackson:

public String serialize(Object obj, boolean pretty) {
    ObjectMapper mapper = new ObjectMapper();

    mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);

    if (pretty) {
        return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
    }

    return mapper.writeValueAsString(obj);
}

这篇关于将对象转储为与Jackson的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆