Search code examples
javajacksongson

dump object to String with Jackson


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

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

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: 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)

Solution

  • To serialize with 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);
    }