json处理-Jackson使用总结

it2026-06-14  5

文章目录

Jackson1 简单映射2 集合及多节点3 配置4 注解5 对日期时间的支持6 处理xml7 集成SpringBoot

Jackson

依赖

<!--jackson依赖--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.11.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.11.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.11.0</version> </dependency>

1 简单映射

@Test public void test1() throws IOException { ObjectMapper mapper = new ObjectMapper(); User user = new User(); user.setName("make"); user.setAge(25); // 写为字符串 String jsonStr = mapper.writeValueAsString(user); System.out.println("1" + jsonStr); // 写为文件 mapper.writeValue(new File("e:/a.txt"),user); // 写为字节流 byte[] bytes = mapper.writeValueAsBytes(user); // 从字符串中读取 User readValueStr = mapper.readValue(jsonStr, User.class); System.out.println("2" + readValueStr); // 从字节流中读取 User readValueBytes = mapper.readValue(bytes, User.class); System.out.println("3" + readValueBytes); // 从文件中读取 User readValueFile = mapper.readValue(new File("e:/a.txt"),User.class); System.out.println("4" + readValueFile); }

2 集合及多节点

@Test void test2() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); Map<String, Object> map = new HashMap<>(); map.put("name","make"); map.put("age",12); map.put("hobby",new String[]{"run","eat","play"}); User user = new User(); user.setName("ming"); user.setAge(24); map.put("user",user); String asString = mapper.writeValueAsString(map); System.out.println(asString); Map<String, Object> asMap = mapper.readValue(asString, // 由于类型擦除关系,这里需要指定类型 new TypeReference<Map<String, Object>>() { }); System.out.println("2"+asMap); // 获得根节点 JsonNode jsonNode = mapper.readTree(asString); int age = jsonNode.get("user").get("age").asInt(); System.out.println(age); // 获得包含所有键值对的迭代器 Iterator<Map.Entry<String, JsonNode>> fields = jsonNode.fields(); while (fields.hasNext()) { // 获得键值对 System.out.println(fields.next()); // 获得Key System.out.println(fields.next().getKey()); } }

3 配置

enable和disable方法则直接启用和禁用相应属性,推荐使用后面两个方法。

// 美化输出 mapper.enable(SerializationFeature.INDENT_OUTPUT); // 允许序列化空的POJO类 // (否则会抛出异常) mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); // 把java.util.Date, Calendar输出为数字(时间戳) mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); // 在遇到未知属性的时候不抛出异常 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // 强制JSON 空字符串("")转换为null对象值: mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT); // 在JSON中允许C/C++ 样式的注释(非标准,默认禁用) mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true); // 允许没有引号的字段名(非标准) mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); // 允许单引号(非标准) mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); // 强制转义非ASCII字符 mapper.configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true); // 将内容包裹为一个JSON属性,属性名由@JsonRootName注解指定 mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);

4 注解

@Data // 指定跟属性名 @JsonRootName("UserTest") // 指定忽略属性 @JsonIgnoreProperties({"ignoreStr","ignoreInt"}) public class User { public User() { } public User(String name, Integer age, String ignoreStr, Integer ignoreInt) { this.name = name; this.age = age; this.ignoreStr = ignoreStr; this.ignoreInt = ignoreInt; } private String name; private Integer age; private String ignoreStr; private Integer ignoreInt; private Like like; } // 指定该类不会被序列化 @JsonIgnoreType class Like{ String s; public Like(String s) { this.s = s; } } @Test public void test3() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); // 开启跟属性名格式 // mapper.enable(SerializationFeature.WRAP_ROOT_VALUE); // 禁用有属性不能转化为对象时报错 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); User user = new User("make",12,"test",24); String asString = mapper.writeValueAsString(user); System.out.println(asString); // {"name":"make","age":12} User readValue = mapper.readValue(asString, User.class); System.out.println(readValue); }

5 对日期时间的支持

@Data public class User { public User(String name, Integer age, LocalDate birthday, Date date) { this.name = name; this.age = age; this.birthday = birthday; this.date = date; } private String name; private Integer age; @JsonFormat(pattern = "yyyy/MM/dd") private LocalDate birthday; @JsonFormat(pattern = "HH mm ss" // 默认是格林威治时间,改为东八区 ,timezone = "GMT+8") private Date date; } @Test public void test5() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); mapper.findAndRegisterModules(); User user = new User("make",24, LocalDate.of(1995,9,10),new Date()); String text = mapper.writeValueAsString(user); System.out.println(text); // {"name":"make","age":24,"birthday":"1995/09/10","date":"15 15 20"} }

6 处理xml

引入依赖

<dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> <version>2.11.0</version> </dependency>

对于JDK9以上的版本,由于实现了模块化管理,需要引入以下依赖

<dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.1</version> </dependency> @Data @JacksonXmlRootElement( // 指定根节点名字 localName = "TestPerson", // 指定命名空间 namespace = "www.ding.org") public class Person { public Person() { } public Person(String name, Integer age, Integer code) { this.name = name; this.age = age; this.code = code; } private String name; private Integer age; @JacksonXmlProperty( // 指定该属性是属性还是节点 isAttribute = true) private Integer code; } @Test void test6() throws JsonProcessingException { XmlMapper xmlMapper = new XmlMapper(); Person person = new Person("make",23,1001); String asString = xmlMapper.writeValueAsString(person); System.out.println(asString); // <TestPerson xmlns="www.ding.org" code="1001"><name xmlns="">make</name><age xmlns="">23</age></TestPerson> Person readValue = xmlMapper.readValue(asString, Person.class); System.out.println(readValue); // Person(name=make, age=23, code=1001) }

7 集成SpringBoot

Spring Boot对Jackson的支持非常完善,只要我们引入相应类库,Spring Boot就可以自动配置开箱即用的Bean。Spring自动配置的ObjectMapper(或者XmlMapper),基本上可以适应大部分情况。

@RestController public class TestController { // springboot已经自动注入了,只需要直接使用即可 @Autowired private ObjectMapper objectMapper; @GetMapping("/test2") public void testx(User user) throws JsonProcessingException { String asString = objectMapper.writeValueAsString(user); System.out.println(asString); } @GetMapping("/test") public User test() throws JsonProcessingException { // 自动使用jackson转换 return new User("make",12, LocalDate.now()); } }
最新回复(0)