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

I am looking for a library function (ideally from a widely used environment like Spring, Guava, Apache Commons, etc.) that will beautifully print the values ​​of any Java object.

This is a general question, not a specific one. Similar questions were noticed in StackOverflow, for which the common answer is “implement your own method toString()in the class”, but this option is not always practical - I’m looking for a general way to do this with any object that I encounter that may arise from third-party code . Another suggestion is to use RefectionToStringBuilder from Apache Commons, for example:

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

But this has limited use - for example, when it encounters a collection, it tends to output something like this:

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

An example of actual use is the log Iterable<PushResult>returned from JGit pushCommand.call()- if you are sending a response, make sure that it will work with this, as well as with any other complex object.

+4
source share
5 answers

You can try using Gson. it also serializes arrays, maps, or something else ....

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 maps .

+1
source

JSON ( ) . "" (, , , , ..), , .

, :

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.
}

:

{
  "id" : 1,
  "list" : [ "A", "B" ]
}
0

GSON . ,

Gson gson = new Gson();
System.out.println(gson.toJson(objectYouWantToPrint).toString());
0

ObjectMapper, json. , :

ObjectMapper mapper = new ObjectMapper();

json ,

Object json = mapper.readValue(input,object.class);

String prettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);

.

0
source

One possible way to do this for any object without using an external library is to use a generic reflection. 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 can be placed in the utility class for easy access.

If any of the fields of the object does not override Object#toString, it simply prints the type of the object and its hash code.

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]]
0
source

Source: https://habr.com/ru/post/1674663/


All Articles