'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.
Solution 1:[1]
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
Solution 2:[2]
You can use the Jackson ObjectMapper
class is use to bind data with json. you can use it like below:
ObjectMapper mapper = new ObjectMapper();
you can save json into object like below
Object json = mapper.readValue(input,object.class);
you can write that in string variable
String prettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
it should work fine.
Solution 3:[3]
One possible way to do this for any object without the use of an external library would be to use reflection of a generic type. In the following snippet, we simply access each field (including private fields) and print their name and value:
public static <T> String printObject(T t) {
StringBuilder sb = new StringBuilder();
for (Field field : t.getClass().getDeclaredFields()) {
field.setAccessible(true);
try {
sb.append(field.getName()).append(": ").append(field.get(t)).append('\n');
} catch (Exception e) {
e.printStackTrace();
}
}
return sb.toString();
}
This method could be placed in a utility class for easy access.
If any of the object's fields do not override Object#toString
it will simply print the object's type and its hashCode.
Example:
public class Test {
private int x = 5;
private int y = 10;
private List<List<Integer>> list = Arrays.asList(Arrays.asList(1, 2, 3), Arrays.asList(4, 5, 6));
}
>> printObject(new Test());
>>
>> x: 5
>> y: 10
>> list: [[1, 2, 3], [4, 5, 6]]
Solution 4:[4]
You can use GSON to convert your object to string. This will work for all the objects,
Gson gson = new Gson();
System.out.println(gson.toJson(objectYouWantToPrint).toString());
Solution 5:[5]
You could use a JSON (or other format) mapper to pretty-print your object. It should handle most "standard" fields (primitives, strings, collections, maps, arrays etc.) and if it doesn't you can always add a custom serialiser.
For example, with Jackson, it could be as simple as this:
public static void main(String... args) throws Exception {
ObjectMapper om = new ObjectMapper();
om.enable(SerializationFeature.INDENT_OUTPUT); //pretty print
String s = om.writeValueAsString(new Pojo());
System.out.println(s);
}
static class Pojo {
private int id = 1;
private List<String> list = Arrays.asList("A", "B");
//getters etc.
}
That code outputs:
{
"id" : 1,
"list" : [ "A", "B" ]
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Community |
Solution 2 | Per Lundberg |
Solution 3 | |
Solution 4 | Max von Hippel |
Solution 5 | assylias |