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

相关文章

python使用库爬取m3u8文件的示例

《python使用库爬取m3u8文件的示例》本文主要介绍了python使用库爬取m3u8文件的示例,可以使用requests、m3u8、ffmpeg等库,实现获取、解析、下载视频片段并合并等步骤,具有... 目录一、准备工作二、获取m3u8文件内容三、解析m3u8文件四、下载视频片段五、合并视频片段六、错误

javax.net.ssl.SSLHandshakeException:异常原因及解决方案

《javax.net.ssl.SSLHandshakeException:异常原因及解决方案》javax.net.ssl.SSLHandshakeException是一个SSL握手异常,通常在建立SS... 目录报错原因在程序中绕过服务器的安全验证注意点最后多说一句报错原因一般出现这种问题是因为目标服务器

gitlab安装及邮箱配置和常用使用方式

《gitlab安装及邮箱配置和常用使用方式》:本文主要介绍gitlab安装及邮箱配置和常用使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1.安装GitLab2.配置GitLab邮件服务3.GitLab的账号注册邮箱验证及其分组4.gitlab分支和标签的

Java实现删除文件中的指定内容

《Java实现删除文件中的指定内容》在日常开发中,经常需要对文本文件进行批量处理,其中,删除文件中指定内容是最常见的需求之一,下面我们就来看看如何使用java实现删除文件中的指定内容吧... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细介绍3.1 Ja

springboot项目中整合高德地图的实践

《springboot项目中整合高德地图的实践》:本文主要介绍springboot项目中整合高德地图的实践,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一:高德开放平台的使用二:创建数据库(我是用的是mysql)三:Springboot所需的依赖(根据你的需求再

spring中的ImportSelector接口示例详解

《spring中的ImportSelector接口示例详解》Spring的ImportSelector接口用于动态选择配置类,实现条件化和模块化配置,关键方法selectImports根据注解信息返回... 目录一、核心作用二、关键方法三、扩展功能四、使用示例五、工作原理六、应用场景七、自定义实现Impor

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

nginx启动命令和默认配置文件的使用

《nginx启动命令和默认配置文件的使用》:本文主要介绍nginx启动命令和默认配置文件的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录常见命令nginx.conf配置文件location匹配规则图片服务器总结常见命令# 默认配置文件启动./nginx

在Windows上使用qemu安装ubuntu24.04服务器的详细指南

《在Windows上使用qemu安装ubuntu24.04服务器的详细指南》本文介绍了在Windows上使用QEMU安装Ubuntu24.04的全流程:安装QEMU、准备ISO镜像、创建虚拟磁盘、配置... 目录1. 安装QEMU环境2. 准备Ubuntu 24.04镜像3. 启动QEMU安装Ubuntu4

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解