带有泛型的序列化
@Testvoid 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);}泛型嵌套的序列化
@Testvoid 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_CNserialization:# 是否开启格式化输出indent_output: false重新注入 ObjectMapper
@Beanpublic 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整合ES+Kibana
- SpringBoot框架SpEL表达式注入漏洞复现与原理分析
- 手写自定义springboot-starter,感受框架的魅力和原理
- 一 JPA入门学习集合springboot
- 2022年实时最新省市区县乡镇街道geojson行政边界数据获取方法
- 关于Springboot启动报错 Whitelabel Error Page: This application has no explicit mapping
- 七 SpringBoot - Redis 缓存
- 五 SpringBoot - Java8 新特性
- 四 SpringBoot - 整合Mybatis,逆向工程,JPA
- 一篇文章带你掌握主流办公框架——SpringBoot
