本案例基于 Springboot 2.5.7 单元测试场景下进行

<!-- SpringMVC默认使用Jacson,只需要引用web启动器即可,无序单独引用Jackson -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Springboot单元测试 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!-- Lombok工具类 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- Hutool工具类 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.3</version>
</dependency>

在后面的测试中会用到的实体类

@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserEntity {
private Integer id;
private String username;
private String password;
private Date birthday;
private LocalDateTime lastLoginDate;
private DeptEntity dept;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class DeptEntity {
private Integer id;
private String name;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result<T> { private int code;
private String msg;
private T data; public static <T> Result<T> success(T data) {
return new Result<>(200, "请求成功", data);
} }

IOC 容器中可以直接获取到 Jackson 的 ObjectMapper 实例

@SpringBootTest
public class SpringTest {
@Autowired
private ObjectMapper mapper;
}

基础类型转换

简单来说就是实体类转换,无论是实体类还是实体类嵌套方法都是一样的

实体类转换

@Test
void test() throws JsonProcessingException {
// 实体类
DeptEntity dept = new DeptEntity(10001, "部门A");
// 序列化
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(dept);
// 反序列化
System.out.println(mapper.readValue(json, DeptEntity.class));
}

实体类嵌套转换

@Test
void test() {
// 实体类
Date birthday = new Date();
LocalDateTime lastLoginDate = LocalDateTime.now();
DeptEntity dept = new DeptEntity(10001, "部门A");
UserEntity user = new UserEntity(10001, "用户A", null, birthday, lastLoginDate, dept);
// 序列化
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user);
// 反序列化
System.out.println(mapper.readValue(json, UserEntity.class));
}

集合类型转换

集合转换简单了解这两种就够了,复杂一点的后面会提到

Collection 集合转换

@Test
void test() throws JsonProcessingException {
// 构建List集合
List<DeptEntity> source = CollUtil.newArrayList();
for (int i = 1; i <= 5; i++) {
source.add(new DeptEntity(10000 + i, "用户" + i));
}
// 序列化
String json = mapper.writeValueAsString(source);
// 构建Type对象
CollectionType type = mapper.getTypeFactory().constructCollectionType(List.class, DeptEntity.class);
// 反序列化
List<DeptEntity> target = mapper.readValue(json, type);
System.out.println(target);
}

Map 集合转换

@Test
void test() throws JsonProcessingException {
// 构建List集合
Map<String, String> source = MapUtil.newHashMap();
source.put("aaa", "哈哈");
source.put("bbb", "呵呵");
// 序列化
String json = mapper.writeValueAsString(source);
// 构建Type对象
MapLikeType type = mapper.getTypeFactory().constructMapLikeType(HashMap.class, String.class, String.class);
// 反序列化
Map<String, String> target = mapper.readValue(json, type);
System.out.println(target);
}

复杂类型转换

这个部分的功能掌握了,类型转换就基本没啥问题了

带有泛型的序列化

@Test
void test() throws JsonProcessingException {
// 实体类
Result<DeptEntity> source = Result.success(new DeptEntity(10001, "部门A"));
// 序列化
String json = mapper.writeValueAsString(source);
// 构建Type对象
JavaType type = mapper.getTypeFactory().constructParametricType(Result.class, DeptEntity.class);
// 反序列化
Result<DeptEntity> target = mapper.readValue(json, type);
System.out.println(target.getData().getClass());
System.out.println(target);
}

泛型嵌套的序列化

@Test
void test() throws JsonProcessingException {
String key = "res";
// 重头戏来了 泛型嵌套的List集合
List<Map<String, Result<DeptEntity>>> source = CollUtil.newArrayList();
Map<String, Result<DeptEntity>> map = MapUtil.newHashMap();
Result<DeptEntity> res = Result.success(new DeptEntity(10001, "部门A"));
map.put(key, res);
source.add(map);
// 序列化
String json = mapper.writeValueAsString(source);
// 构建Type对象
SimpleType stringType = SimpleType.constructUnsafe(String.class);
JavaType result = mapper.getTypeFactory().constructParametricType(Result.class, DeptEntity.class);
MapLikeType mapType = mapper.getTypeFactory().constructMapLikeType(HashMap.class, stringType, result);
CollectionType type = mapper.getTypeFactory().constructCollectionType(List.class, mapType);
// 反序列化
List<Map<String, Result<DeptEntity>>> target = mapper.readValue(json, type);
System.out.println(target.get(0).get(key).getData().getClass());
System.out.println(target.get(0).get(key).getClass());
System.out.println(target.get(0).getClass());
System.out.println(target.getClass());
System.out.println(target);
}

Jackson 的配置项

常见的用法是把 Controller 回传给前端的 JSON 进行一些处理,例如时间格式化、忽略 NULL 值等等

这些配置可以在配置文件中完成,可以重新注入ObjectMapper,也可以使用实体类注解单独配置

这部分内容用到哪些配置项,想起来就补充,随缘更新

配置文件

spring:
jackson:
# 格式化日期时使用的时区
time-zone: GMT+8
# 格式化
date-format: yyyy-MM-dd HH:mm:ss.SSS
# 用于格式化的语言环境
locale: zh_CN
serialization:
# 是否开启格式化输出
indent_output: false

重新注入 ObjectMapper

@Bean
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
// 通过该方法对mapper对象进行设置,所有序列化的对象都将该规则进行序列化
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
// Include.Include.ALWAYS 默认
// Include.NON_DEFAULT 属性为默认值不序列化
// Include.NON_EMPTY 属性为 空("") 或者为 NULL 都不序列化,则返回的json是没有这个字段的。这样对移动端会更省流量
// Include.NON_NULL 属性为NULL 不序列化
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return objectMapper;
}

实体类注解

注解 作用
@JsonIgnoreProperties 批量设置转 JSON 时忽略的属性
@JsonIgnore 转 JSON 时忽略当前属性
@JsonProperty 修改转换后的 JSON 的属性名
@JsonFormat 转 JSON 时格式化属性的值

Springboot JSON 转换:Jackson篇的更多相关文章

  1. @JsonCreator自定义反序列化函数-JSON框架Jackson精解第5篇

    Jackson是Spring Boot(SpringBoot)默认的JSON数据处理框架,但是其并不依赖于任何的Spring 库.有的小伙伴以为Jackson只能在Spring框架内使用,其实不是的, ...

  2. Jackson框架,json转换

    Jackson可以轻松的将Java对象转换成json对象和xml文档,同样也可以将json.xml转换成Java对象. 前面有介绍过json-lib这个框架,在线博文:http://www.cnblo ...

  3. Springboot单例模式实战封装json转换

    一.定义 保证一个类仅有一个实例,并提供一个全局访问点. 二.优点 (1)在内存里只有一个实例,减少了内存开销      (2)可以避免对资源的多重占用      (3)设置全局访问点,严格控制访问 ...

  4. 【Json】Jackson将json转换成泛型List

    Jackson将json转换成泛型List 获取泛型类型 /** * 获取泛型类型 * * @return */ protected Class<T> getGenericsType() ...

  5. Spring学习---Spring中利用jackson进行JSON转换

    Spring中利用jackson进行JSON转换 import java.util.List; import com.fasterxml.jackson.core.JsonProcessingExce ...

  6. URL及日期等特殊数据格式处理-JSON框架Jackson精解第2篇

    Jackson是Spring Boot默认的JSON数据处理框架,但是其并不依赖于任何的Spring 库.有的小伙伴以为Jackson只能在Spring框架内使用,其实不是的,没有这种限制.它提供了很 ...

  7. 属性序列化自定义与字母表排序-JSON框架Jackson精解第3篇

    Jackson是Spring Boot默认的JSON数据处理框架,但是其并不依赖于任何的Spring 库.有的小伙伴以为Jackson只能在Spring框架内使用,其实不是的,没有这种限制.它提供了很 ...

  8. Springboot中redisTemplate乱码或json转换问题

    问题1 用RedisTemplate存入map值的时候,用rdm可视化打开,看到的是转码之后的数据,如图: 存入的方法为: public boolean hmset(String key, Map&l ...

  9. java json转换

    https://blog.csdn.net/WillJGL/article/details/77866224 SpringBoot中如果需要实现json的序列化和反序列化,我们会使用json解析工具. ...

随机推荐

  1. MyBatis-Plus 配置文件

    MyBatis-Plus在实际工作中常用到的配置,供自己和大家查阅学习. mybatis-plus: mapperPackage: com.**.**.mapper # 对应的 XML 文件位置 ma ...

  2. ceph 006 rbd高级特性 rbd快照 镜像克隆 rbd缓存 rbd增量备份 rbd镜像单向同步

    版本 [root@clienta ~]# ceph -v ceph version 16.2.0-117.el8cp (0e34bb74700060ebfaa22d99b7d2cdc037b28a57 ...

  3. 记Windows服务器Redis 6379被攻击 被设置主从模式同步项目数据

    在工作中第一次经历被攻击,我是一个前端,同时复负责维护一个已上线的项目,在最近一段时间小程序与后台经常出现这个报错, 搜了下说我的从机是只读模式,不能写入,问了同事得知这个项目是单机模式,根本不存在从 ...

  4. java-异步与并发之基础

    1.线程提供了一个方法: void join()该方法允许一个线程在另一个线程上等待,直到其完成工作后才解除阻塞运行.所以join可以协调线程之间同步运行线程调用join()方法,方法后就进入阻塞状态 ...

  5. 小技巧---eclipse 全选lib jar包

    按住shift键,点击第一个jar包,然后点击最后一个jar包,就全选了所有jar包,然后添加build path 添加到类路径

  6. day27--Java集合10

    Java集合10 21.集合家庭作业 21.1Homework01 按要求实现: 封装一个新闻类,包括标题和内容属性,提供get.set方法,重写toString方法,打印对象时只打印标题: 只提供一 ...

  7. 【Java】学习路径47-线程锁synchronized

    线程安全问题: 简单来说,就是多个线程在操作同一个变量时引起的问题. 这里是用一个简单的例子说明一下: 以Runnable创建的线程为例:一个售票系统,count代表当前票数,卖出一张count--. ...

  8. dotnet 设计规范 · 数组定义

    ✓ 建议在公开的 API 使用集合而不是数组.集合可以提供更多的信息. X 不建议设置数组类型的字段为只读.虽然用户不能修改字段,但是可以修改字段里面的元素.如果需要一个只读的集合,建议定义为只读集合 ...

  9. SpringMVC 07: WEB-INF下的资源访问 + SpringMVC拦截器

    WBE-INF目录下的资源访问 项目配置和Spring博客集(指SpringMVC 02)中配置一样 出于对网站资源的安全性保护,放在WBE-INF目录下的资源不可以被外部直接访问 在WEB-INF/ ...

  10. 深度剖析js闭包

    一.什么是闭包? 方法里面返回一个方法 二.闭包存在的意义 延长变量的生命周期 作用域链 沟通内外部方法的桥梁    闭包会常驻内存  ==>慎用闭包  闭包里的变量不会被回收 创建私有环建 例 ...