Skip to content
Advertisement

How to pretty print a complex Java object (e.g. with fields that are collections of objects)? [closed]

I’m looking for a library function (ideally from a commonly used framework e.g. Spring, Guava, Apache Commons etc.) that will nicely print the values of any Java object.

This is a general question rather than a specific one. Have seen similar questions on StackOverflow for which a common answer is “implement your own toString() method on the class” but this option isn’t always practical – am looking for a general way of doing this with any object I come across, which may originate from third party code. Another suggestion is to use RefectionToStringBuilder from Apache Commons, e.g:

new ReflectionToStringBuilder(complexObject, new RecursiveToStringStyle()).toString()

But this has limited use – e.g. when it comes across a collection it tends to output something like this:

java.util.ArrayList@fcc7ab1[size=1]

An actual use case example is to log an Iterable<PushResult> returned from JGit’s pushCommand.call() method – if posting an answer please make sure it would work with this as well as any other complex object.

Advertisement

Answer

You could try and use Gson. it also serializes Arrays, Maps or whatever….

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

For deserialization use:

gson.fromJson(MyObject.class);

For typed maps see this answer: Gson: Is there an easier way to serialize a map

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement