Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dump object to String with Jackson

Tags:

java

gson

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) 
like image 823
turbanoff Avatar asked Mar 19 '12 08:03

turbanoff


People also ask

How does Jackson convert object to JSON?

Converting Java object to JSON In it, create an object of the POJO class, set required values to it using the setter methods. Instantiate the ObjectMapper class. Invoke the writeValueAsString() method by passing the above created POJO object. Retrieve and print the obtained JSON.

What is the use of writerWithDefaultPrettyPrinter ()?

We can Pretty print JSON using the writerWithDefaultPrettyPrinter() of ObjectMapper class, it is a factory method for constructing ObjectWriter that will serialize objects using the default pretty printer for indentation.

What does ObjectMapper readValue do?

The simple readValue API of the ObjectMapper is a good entry point. We can use it to parse or deserialize JSON content into a Java object. Also, on the writing side, we can use the writeValue API to serialize any Java object as JSON output.


1 Answers

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); } 
like image 62
Bruno Grieder Avatar answered Oct 14 '22 08:10

Bruno Grieder