package com.example.demo; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; public class JsonFormattingExample { public static void main(String[] args) throws Exception { // 创建ObjectMapper对象 ObjectMapper objectMapper = new ObjectMapper(); // 创建一个空的JSON对象 JsonNode jsonNode = objectMapper.createObjectNode(); // 设置属性 ((ObjectNode) jsonNode).put("name", "John"); ((ObjectNode) jsonNode).put("age", 25); // 将JSON对象转换为字符串 String jsonString = objectMapper.writeValueAsString(jsonNode); //未格式化的字符串 System.out.println(jsonString); // 格式化JSON字符串 String formattedJsonString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode); // 输出格式化后的JSON字符串 System.out.println(formattedJsonString); } }
json字符串格式化
发表评论