Java ObjectMapper 格式化输出 JSON

Java JSON Jackson About 755 words

优雅输出

使用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

Views: 7,026 · Posted: 2020-05-27

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

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

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


Today On History
Browsing Refresh