Java ObjectMapper格式化输出JSON

JavaJSON大约 754 字

优雅输出

使用writerWithDefaultPrettyPrinter方法。

public static void main(String[] args) throws JsonProcessingException {
    User user = new User();
    user.age = 20;
    user.username = "test";
    user.hobbies = Arrays.asList("x", "y", "z").toArray(new String[]{});
    user.phones = new HashSet<String>(Arrays.asList("a", "b", "c"));
    user.valid = true;

    ObjectMapper objectMapper = new ObjectMapper();
    String value = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(user);
    System.out.println(value);
}

输出

{
  "age" : 20,
  "username" : "test",
  "hobbies" : [ "x", "y", "z" ],
  "phones" : [ "a", "b", "c" ],
  "valid" : true
}

完整代码

https://github.com/fendoudebb/learning/tree/master/java/learn-spring-boot/object-mapper

阅读 343 · 发布于 2020-05-27

————        END        ————

扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看换一批