【序列化与反序列化】Jackson
1. jackson序列化和反序列化
依赖<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.8</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.8</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.9.0</version> </dependency> 或者以下依赖 (spring-boot-starter-web包含了以上依赖) <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.1.5.RELEASE</version> </dependency>
示例
package com.chenly.serialize.jackson; import com.chenly.serialize.bean.Score; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import java.util.Date; /** * @author: chenly * @date: 2022-11-28 16:48 * @description: * @version: 1.0 */ public class JacksonTest { public static void main(String[] args) { Score score1 = Score.builder() .className("一班") .createDate(new Date()) .stuName("张三").course("生物").score(90).build(); ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().build(); byte[] bytes ; Object object; try { //序列化成json字符串 String jsonStr = objectMapper.writeValueAsString(score1); System.out.println(jsonStr); //反序列化 object = objectMapper.readValue(jsonStr,Score.class); System.out.println(object); //序列化成byte bytes = objectMapper.writeValueAsBytes(score1); //反序列化 object = objectMapper.readValue(bytes,Score.class); System.out.println(object); } catch (Exception e) { e.printStackTrace(); } } }
2. jackson常用注解
Jackson 包含了很多注解,用来个性化序列化和反序列化操作,主要包含如下注解。
- @JsonProperty:作用在属性上,用来为JSON Key指定一个别名
- @JsonIgnore:作用在属性上,用来忽略此属性
- @JsonIgnoreProperties:作用在类上,忽略一组属性,比如@JsonIgnoreProperties({"id","name"})
- @JsonFormat:作用在属性上,用于日期的格式化,如:
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date createDate;
参考地址
1、https://www.cnblogs.com/cnjavahome/p/8393178.html
作者:小念
本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。