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)
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.
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.
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.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With