springboot学习(四十六) springboot中jackson特殊使用

2024-06-20 08:18

本文主要是介绍springboot学习(四十六) springboot中jackson特殊使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1、全局时间配置
在application.yml中配置

spring:jackson:date-format: yyyy-MM-dd HH:mm:ss

或在application.properties中配置

spring.jackson.date-format=yyyy-MM-dd HH:mm:ss

实体中包含时间类型:

/**** @author zhuquanwen* @vesion 1.0* @date 2021/6/14 14:06* @since jdk1.8*/
@Data
@Builder
public class Model {private Integer id;private int age;private String name;private Date createTime;
}

测试controller:

/**** @author zhuquanwen* @vesion 1.0* @date 2021/6/14 14:08* @since jdk1.8*/
@RestController
@RequestMapping("/jackson/type1")
public class JacksonType1Controller {@GetMapping("/res")public Model res() {return Model.builder().id(1).age(12).name("xiaoxiao").createTime(new Date()).build();}
}

测试结果:
在这里插入图片描述
2、使用@JsonFormat为某个属性设置序列化方式
实体:

/**** @author zhuquanwen* @vesion 1.0* @date 2021/6/14 14:06* @since jdk1.8*/
@Data
@Builder
public class Model {private Integer id;private int age;private String name;@JsonFormat(pattern = "yyyy/MM/dd HH:mm:ss")private Date createTime;
}

测试controller:

/**** @author zhuquanwen* @vesion 1.0* @date 2021/6/14 14:08* @since jdk1.8*/
@RestController
@RequestMapping("/jackson/type2")
public class JacksonType2Controller {@GetMapping("/res")public Model res() {return Model.builder().id(1).age(12).name("xiaoxiao").createTime(new Date()).build();}
}

测试结果:
在这里插入图片描述
3、使用@JsonPropertyOrder调整属性的序列化顺序
实体:

/***** @author zhuquanwen* @vesion 1.0* @date 2021/6/14 14:06* @since jdk1.8*/
@Data
@Builder
@JsonPropertyOrder(value={"name", "age"})
public class Model {private Integer id;private int age;private String name;private Date createTime;
}

controller:

/**** @author zhuquanwen* @vesion 1.0* @date 2021/6/14 14:08* @since jdk1.8*/
@RestController
@RequestMapping("/jackson/type3")
public class JacksonType3Controller {@GetMapping("/res")public Model res() {return Model.builder().id(1).age(12).name("xiaoxiao").createTime(new Date()).build();}
}

测试结果:
在这里插入图片描述
4、使用@JsonProperty修改属性名称
实体:

/***** @author zhuquanwen* @vesion 1.0* @date 2021/6/14 14:06* @since jdk1.8*/
@Data
@Builder
public class Model {private Integer id;private int age;//调整序列化的名称@JsonProperty("myName")private String name;private Date createTime;
}

controller:

/**** @author zhuquanwen* @vesion 1.0* @date 2021/6/14 14:08* @since jdk1.8*/
@RestController
@RequestMapping("/jackson/type4")
public class JacksonType4Controller {@GetMapping("/res")public Model res() {return Model.builder().id(1).age(12).name("xiaoxiao").createTime(new Date()).build();}
}

测试结果:
在这里插入图片描述
5、使用@JsonInclude使属性值为null不参与序列化
实体:

/***** @author zhuquanwen* @vesion 1.0* @date 2021/6/14 14:06* @since jdk1.8*/
@Data
@Builder
public class Model {@JsonInclude(value= JsonInclude.Include.NON_NULL)private Integer id;private int age;private String name;private Date createTime;
}

controller:

/**** @author zhuquanwen* @vesion 1.0* @date 2021/6/14 14:08* @since jdk1.8*/
@RestController
@RequestMapping("/jackson/type5")
public class JacksonType5Controller {@GetMapping("/res")public Model res() {return Model.builder().age(12).name("xiaoxiao").createTime(new Date()).build();}
}

测试结果:
在这里插入图片描述
6、使用@JsonIgnore使某个属性不参与序列化
实体:

/***** @author zhuquanwen* @vesion 1.0* @date 2021/6/14 14:06* @since jdk1.8*/
@Data
@Builder
public class Model {@JsonIgnoreprivate Integer id;private int age;private String name;private Date createTime;
}

controller:

/**** @author zhuquanwen* @vesion 1.0* @date 2021/6/14 14:08* @since jdk1.8*/
@RestController
@RequestMapping("/jackson/type6")
public class JacksonType6Controller {@GetMapping("/res")public Model res() {return Model.builder().id(1).age(12).name("xiaoxiao").createTime(new Date()).build();}
}

测试结果:
在这里插入图片描述
7、自定义注解实现序列化和反序列化

将字符串转为数组的序列化处理

package com.iscas.base.biz.test.service;import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.iscas.common.web.tools.json.JsonUtils;import java.io.IOException;
import java.util.List;
import java.util.Objects;/*** @author zhuquanwen* @version 1.0* @date 2022/6/6 14:04* @since jdk11*/
public class CustomSerialize extends JsonSerializer<String> implements ContextualSerializer {@Overridepublic void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {if (value == null) {gen.writeNull();} else {TypeReference<List<String>> typeReference = new TypeReference<>() {};gen.writeObject(JsonUtils.fromJson(value, typeReference));}}@Overridepublic JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {//判断beanProperty是不是空if (property == null){return prov.findNullValueSerializer(property);}//判断类型是否是Stringif (Objects.equals(property.getType().getRawClass(),String.class)){CustomStrFormatter annotation = property.getAnnotation(CustomStrFormatter.class);if (annotation != null){// 这里可以获取注解中的一些参数String pattern = annotation.pattern();return this;}}return prov.findValueSerializer (property.getType (), property);}
}

将数组反序列化为JSON字符串的处理

package com.iscas.base.biz.test.service;import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.iscas.common.web.tools.json.JsonUtils;
import org.apache.commons.lang3.StringUtils;import java.util.ArrayList;
import java.util.List;
import java.util.Objects;/*** @author zhuquanwen* @version 1.0* @date 2022/6/6 14:04* @since jdk11*/
public class CustomDeserialize extends JsonDeserializer<String> implements ContextualDeserializer {@Overridepublic String deserialize(JsonParser p, DeserializationContext ctxt) {try {if (p != null && StringUtils.isNotEmpty(p.getText())) {List<String> strs = new ArrayList<>();JsonToken jsonToken;while (!p.isClosed() && (jsonToken = p.nextToken()) != null && !JsonToken.FIELD_NAME.equals(jsonToken) &&!JsonToken.END_ARRAY.equals(jsonToken)) {strs.add(p.getValueAsString());}return JsonUtils.toJson(strs);} else {return null;}} catch (Exception e) {throw new RuntimeException(e);}}@Overridepublic JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException {//判断beanProperty是不是空if (property == null) {return ctxt.findNonContextualValueDeserializer(property.getType());}//判断类型是否是Stringif (Objects.equals(property.getType().getRawClass(), String.class)) {CustomStrFormatter annotation = property.getAnnotation(CustomStrFormatter.class);if (annotation != null) {// 这里可以获取注解中的一些参数String pattern = annotation.pattern();return this;}}return ctxt.findContextualValueDeserializer(property.getType(), property);}
}

自定义注解

package com.iscas.base.biz.test.service;import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;/*** @author zhuquanwen* @version 1.0* @date 2022/6/6 14:02* @since jdk11*/
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonSerialize(using = CustomSerialize.class)
@JsonDeserialize(using = CustomDeserialize.class)
public @interface CustomStrFormatter {// todo 可以定义格式化方式String pattern() default "";
}

实体中使用自定义注解

  @Data@Accessors(chain = true)public static class TestModel {private String id;private List<String> strs1;@CustomStrFormatterprivate String strs2;}

测试:

@RequestMapping("/test/serial")
@RestController
@Slf4j
public class TestJsonFormatterController {/*** 测试序列化* */@GetMappingpublic TestModel test1() {TestModel testModel = new TestModel();testModel.setId("1").setStrs1(List.of("1", "2", "3")).setStrs2("[\"3\", \"4\"]");return testModel;}@PostMappingpublic String test2(@RequestBody TestModel testModel) {log.info("接收到的testModel:{}", testModel.toString());return "success";}
}

这篇关于springboot学习(四十六) springboot中jackson特殊使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1077593

相关文章

Java中流式并行操作parallelStream的原理和使用方法

《Java中流式并行操作parallelStream的原理和使用方法》本文详细介绍了Java中的并行流(parallelStream)的原理、正确使用方法以及在实际业务中的应用案例,并指出在使用并行流... 目录Java中流式并行操作parallelStream0. 问题的产生1. 什么是parallelS

Linux join命令的使用及说明

《Linuxjoin命令的使用及说明》`join`命令用于在Linux中按字段将两个文件进行连接,类似于SQL的JOIN,它需要两个文件按用于匹配的字段排序,并且第一个文件的换行符必须是LF,`jo... 目录一. 基本语法二. 数据准备三. 指定文件的连接key四.-a输出指定文件的所有行五.-o指定输出

Java中Redisson 的原理深度解析

《Java中Redisson的原理深度解析》Redisson是一个高性能的Redis客户端,它通过将Redis数据结构映射为Java对象和分布式对象,实现了在Java应用中方便地使用Redis,本文... 目录前言一、核心设计理念二、核心架构与通信层1. 基于 Netty 的异步非阻塞通信2. 编解码器三、

Linux jq命令的使用解读

《Linuxjq命令的使用解读》jq是一个强大的命令行工具,用于处理JSON数据,它可以用来查看、过滤、修改、格式化JSON数据,通过使用各种选项和过滤器,可以实现复杂的JSON处理任务... 目录一. 简介二. 选项2.1.2.2-c2.3-r2.4-R三. 字段提取3.1 普通字段3.2 数组字段四.

Linux kill正在执行的后台任务 kill进程组使用详解

《Linuxkill正在执行的后台任务kill进程组使用详解》文章介绍了两个脚本的功能和区别,以及执行这些脚本时遇到的进程管理问题,通过查看进程树、使用`kill`命令和`lsof`命令,分析了子... 目录零. 用到的命令一. 待执行的脚本二. 执行含子进程的脚本,并kill2.1 进程查看2.2 遇到的

SpringBoot基于注解实现数据库字段回填的完整方案

《SpringBoot基于注解实现数据库字段回填的完整方案》这篇文章主要为大家详细介绍了SpringBoot如何基于注解实现数据库字段回填的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以了解... 目录数据库表pom.XMLRelationFieldRelationFieldMapping基础的一些代

一篇文章彻底搞懂macOS如何决定java环境

《一篇文章彻底搞懂macOS如何决定java环境》MacOS作为一个功能强大的操作系统,为开发者提供了丰富的开发工具和框架,下面:本文主要介绍macOS如何决定java环境的相关资料,文中通过代码... 目录方法一:使用 which命令方法二:使用 Java_home工具(Apple 官方推荐)那问题来了,

Java HashMap的底层实现原理深度解析

《JavaHashMap的底层实现原理深度解析》HashMap基于数组+链表+红黑树结构,通过哈希算法和扩容机制优化性能,负载因子与树化阈值平衡效率,是Java开发必备的高效数据结构,本文给大家介绍... 目录一、概述:HashMap的宏观结构二、核心数据结构解析1. 数组(桶数组)2. 链表节点(Node

Java AOP面向切面编程的概念和实现方式

《JavaAOP面向切面编程的概念和实现方式》AOP是面向切面编程,通过动态代理将横切关注点(如日志、事务)与核心业务逻辑分离,提升代码复用性和可维护性,本文给大家介绍JavaAOP面向切面编程的概... 目录一、AOP 是什么?二、AOP 的核心概念与实现方式核心概念实现方式三、Spring AOP 的关

详解SpringBoot+Ehcache使用示例

《详解SpringBoot+Ehcache使用示例》本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录摘要概念内存与磁盘持久化存储:配置灵活性:编码示例引入依赖:配置ehcache.XML文件:配置