Pretty-print a Map in Java

前端 未结 16 1187
傲寒
傲寒 2020-12-04 10:11

I am looking for a nice way to pretty-print a Map.

map.toString() gives me: {key1=value1, key2=value2, key3=value3}

I

16条回答
  •  心在旅途
    2020-12-04 10:46

    I prefer to convert the map to a JSON string it is:

    • a standard
    • human readable
    • supported in editors like Sublime, VS Code, with syntax highlighting, formatting and section hide/show
    • supports JPath so editors can report exactly which part of the object you have navigated to
    • supports nested complex types within the object

      import com.fasterxml.jackson.core.JsonProcessingException;
      import com.fasterxml.jackson.databind.ObjectMapper;
      
      public static String getAsFormattedJsonString(Object object)
      {
          ObjectMapper mapper = new ObjectMapper();
          try
          {
              return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
          }
          catch (JsonProcessingException e)
          {
              e.printStackTrace();
          }
          return "";
      }
      

提交回复
热议问题