zoukankan      html  css  js  c++  java
  • 用jackson输出标准的json字符串

     1 public class JacksonObjectMapperExample {
     2 
     3     public static String formatJson(String jsonStr) throws IOException {
     4         ObjectMapper objectMapper = new ObjectMapper();
     5         // 允许没有引号的字段名(非标准)
     6         objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
     7         // 允许单引号(非标准)
     8         objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
     9         Object json = objectMapper.readValue(jsonStr, Object.class);
    10         //美化
    11         //System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(json));
    12         //objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    13         //不美化
    14         objectMapper.configure(SerializationFeature.INDENT_OUTPUT, false);
    15 
    16         return objectMapper.writeValueAsString(json);
    17     }
    18 
    19     public static void main(String[] args) throws IOException {
    20         String test = "{age:29,messages:["msg 1","msg 2","msg 3"],"name":"mkyong"}";
    21         System.out.println(formatJson(test));
    22     }
    23 }
  • 相关阅读:
    202103226-1 编程作业
    阅读任务
    1 20210309-1 准备工作
    20210405-1 案例分析作业
    第一周作业
    20210309-2 阅读任务
    20210309-1 准备工作
    编程作业
    阅读任务
    准备工作
  • 原文地址:https://www.cnblogs.com/yasepix/p/10009220.html
Copyright © 2011-2022 走看看