Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 472
Steve Chambers Avatar asked Apr 12 '17 13:04

Steve Chambers


People also ask

What is pretty print in Java?

Prettyprint is the process of converting and presenting source code or other objects in a legible and attractive way. A prettyprinter takes blocks of code and prints them in an aesthetically pleasing fashion, presenting the characters with line breaks and indentations to make the code comprehensible.

How can we print object in Java?

The print(Object) method of PrintStream Class in Java is used to print the specified Object on the stream. This Object is taken as a parameter. Parameters: This method accepts a mandatory parameter object which is the Object to be printed in the Stream. Return Value: This method do not returns any value.


1 Answers

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

like image 60
Naxos84 Avatar answered Sep 27 '22 21:09

Naxos84