Json格式化输出

主要目的就是格式化输出JSON,这样将输出的字符串直接写入本地文件作为配置文件,阅读起来也比较方便。
另外推荐ToStringBuilder,在apache的common-lang3中,输出对象时比较直观方便。

        1.9.2

        
            org.codehaus.jackson
            jackson-core-asl
            ${jackson.version}
        
        
            org.codehaus.jackson
            jackson-mapper-asl
            ${jackson.version}
        

样例代码:

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            PropCluster obj = new PropCluster();
            Map map = new HashMap<>();
            for (int i = 0; i < 5; i++) {
                map.put("key" + i, "value" + i);
            }
            obj.setPropMap(map);
            obj.setVersion(2);
            String prettyStr = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
            System.out.println(prettyStr);

            obj = JsonUtil.fromObject(prettyStr, PropCluster.class);
            System.out.println(ToStringBuilder.reflectionToString(obj, ToStringStyle.MULTI_LINE_STYLE));
        } catch (Exception e) {
            e.printStackTrace();
        }

输出结果

  "propMap" : {
    "key1" : "value1",
    "key2" : "value2",
    "key0" : "value0",
    "key3" : "value3",
    "key4" : "value4"
  },
  "version" : 2
}
com.fm.propClient.domain.PropCluster@1623b78d[
  propMap={key1=value1, key2=value2, key0=value0, key3=value3, key4=value4}
  version=2
]

你可能感兴趣的:(Json格式化输出)