如何在Java中,使用jackson实现json缩进美化

导入的maven依赖

<!--json-->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.10.0</version>
</dependency>

示例代码

json要是String类型

public static void main(String[] args) throws Exception {
        String requestJson1 = "{\n" +
                "  \"header\": {\n" +
                "    \"app_id\": \"" + appid + "\",\n" +
                "    \"status\":2\n" +
                "  },\n" +
                "  \"parameter\": {\n" +
                "    \"s15282f39\": {\n" +
                "      \"category\": \"ch_en_public_cloud\",\n" +
                "      \"result\": {\n" +
                "        \"encoding\": \"utf8\",\n" +
                "        \"compress\": \"raw\",\n" +
                "        \"format\": \"plain\"\n" +
                "      }\n" +
                "    },\n" +
                "    \"s5eac762f\": {\n" +
                "      \"result_type\": \"" + RESULT_TYPE + "\",\n" +
                "      \"result\": {\n" +
                "        \"encoding\": \"utf8\",\n" +
                "        \"compress\": \"raw\",\n" +
                "        \"format\": \"plain\"\n" +
                "      }\n" +
                "    }\n" +
                "  },\n" +
                "  \"payload\": {\n" +
                "    \"test\": {\n" +
                "      \"encoding\": \"" + "a" + "\",\n" +
                "      \"image\": \"" + "11" + "\",\n" + "      \"status\": 3\n" + "    }\n" + "  }\n" + "}";

        prettyPrint(requestJson1);
        ObjectMapper mapper = new ObjectMapper();        
        Object obj = mapper.readValue(requestJson1, Object.class);
        System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj));
    }
}

输出效果的json示例

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值