自定义类继承JsonSerializer


import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.ctsec.mse.exception.ApiException;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import lombok.extern.slf4j.Slf4j;/*** 自定义JSON 序列化* 类型为String 值为null 时 输出 ""* @author ZJ.Fang* @date 2022/6/29 17:14*/
@Slf4j
public class MyObjectSerialize<T> extends JsonSerializer<T> {@Overridepublic void serialize(T obj, JsonGenerator generator, SerializerProvider serializers) throws IOException {generator.writeStartObject();writeObj(obj, generator);generator.writeEndObject();}private void writeObj(T obj, JsonGenerator generator) throws IOException {Field[] fields = ReflectUtil.getFields(obj.getClass());for (Field field : fields) {JsonIgnore annotation = field.getAnnotation(JsonIgnore.class);Method readMethod = getReadMethod(field, obj);if (annotation != null || readMethod == null) {continue;}generator.writeFieldName(getFieldName(field));generator.writeObject(getFieldValue(field, obj));}}private String getFieldName(Field field) {String fieldName;JsonProperty jsonProperty = field.getAnnotation(JsonProperty.class);if (jsonProperty != null && StrUtil.isNotBlank(jsonProperty.value())) {fieldName = jsonProperty.value();} else {fieldName = field.getName();}return fieldName;}private Object getFieldValue(Field field, Object obj) {try {Method readMethod = getReadMethod(field, obj);if (readMethod == null) {return null;}Object value = readMethod.invoke(obj);Object defaultValue = defaultAnnotationValue(field);if (value == null && defaultValue != null) {return defaultValue;} else if(value == null && field.getType().equals(String.class)) {return "";}else{return value;}} catch (IllegalAccessException | InvocationTargetException e) {log.error(e.getMessage(), e);throw new ApiException(500, "JSON序列化异常:" + e.getMessage());}}private Object defaultAnnotationValue(Field field) {JsonProperty annotation = field.getAnnotation(JsonProperty.class);if (annotation == null) {return null;}String s = annotation.defaultValue();return convertDefaultValueType(field, s);}private Object convertDefaultValueType(Field field, String value) {return Convert.convert(field.getType(), value);}private Method getReadMethod(Field field, Object obj) {String name = field.getName();String getterName = parGetName(name);return ReflectUtil.getMethodByName(obj.getClass(), getterName);}/*** 拼接某属性的 get方法*/public static String parGetName(String fieldName) {if (StrUtil.isNotBlank(fieldName)) {int startIndex = 0;if (fieldName.charAt(0) == '_') {startIndex = 1;}return "get" + fieldName.substring(startIndex, startIndex + 1).toUpperCase() + fieldName.substring(startIndex + 1);}return null;}}

使用

@JsonSerialize(using = MyObjectSerialize.class)
public class PersonDTO {// Fields、Getter、Setter ...
}

SpringBoot自定义JSON序列化规则相关推荐

  1. .NET 自定义Json序列化时间格式

    .NET 自定义Json序列化时间格式 Intro 和 JAVA 项目组对接,他们的接口返回的数据是一个json字符串,里面的时间有的是Unix时间戳,有的是string类型,有的还是空,默认序列化规 ...

  2. Spring Session Redis——自定义JSON序列化解决方案

    问题描述 Spring Session + Redis--自定义JSON序列化解决方案 问题分析 RedisHttpSessionConfiguration中,Bean名称必须是springSessi ...

  3. 【Go】自定义json序列化

    一.忽略字段 我们知道,通过tag,可以有条件地实现定制Go JSON序列化的方式,比如json:"abc,omitempty", 当字段的值为空的时候,我们可以在序列化后的数据中 ...

  4. DateOnly和TimeOnly类型居然不能序列化!!! .Net 6下实现自定义JSON序列化

    前言 .Net 6引入了DateOnly和TimeOnly结构,可以存储日期和时间. 但在实际使用时,发现一个很尴尬的问题,DateOnly和TimeOnly居然不能被序列化: var builder ...

  5. 【玩转Golang】 自定义json序列化对象时,非法字符错误原因

    由于前台web页面传来的日期对象是这样的格式"2010-11-03 15:23:22",所以我安装网上查来的办法,自定义包装了time.Time对象,实现自己的Marshal和Un ...

  6. Spring Security——集成Spring Session、Redis和JSON序列化解决方案

    官方文档 https://docs.spring.io/spring-session/docs/2.4.2/reference/html5/#spring-security Maven 主要 < ...

  7. json序列化定义类型jsckson

    可以解决一批问题. 1.导包 <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databin ...

  8. Redis整合SpringBoot,出现“\xac\xed\x00\x05t\x00\x03解决自定义RedisTemplate序列化

    SpringBoot整合 SpringBoot操作数据:spring-data jpa jdbc mongodb redis SpringData也是和SpringBoot齐名的项目 说明:在Spri ...

  9. SpringBoot配置跨域 修改默认json序列化

    SpringBoot配置跨域 修改默认json序列化 修改跨域 addCorsMappings(CorsRegistry registry)方法添加跨域设置的,无法生效,原因是请求经过的先后顺序问题, ...

最新文章

  1. 算法-判断一颗树是否是搜索二叉树
  2. 来做一做你是三国里的哪一个人物呢
  3. 基于Pytorch再次解读GoogLeNet现代卷积神经网络
  4. 关于python文件_关于python文件操作
  5. Qt Creator 代码自动补全设置
  6. adb shell命令_[Android]adb的使用
  7. gb50243-2016通风与空调工程施工质量验收规范_【规范】现行建筑标准规范集合:(六)专业工程...
  8. 写给自己--70年代的程序员
  9. @bean 什么时候执行_离婚冷静期什么时候开始执行?
  10. django 分页(2) 使用类 页码显示
  11. 基于c语言图书管理系统设计与开发,基于C语言图书管理系统设计与实现.doc
  12. kali初学——nmap扫描
  13. java free hd 798,[https://www.798ziyuan.com/]Java入门级项目全程实录V2.0
  14. 天下武功唯快不破------实验吧
  15. 我是谁?——第一次CSDN发文
  16. 阿里定向广告最新突破:面向下一代的粗排排序系统 COLD
  17. 翡翠玉石微观世界,太美了!
  18. 非常喜欢的一期《晓松奇谈》
  19. android屏幕录制功能,Android利用ADB进行屏幕录制
  20. php怎么自动识别车牌号,你知道车牌识别系统是如何自动识别车牌的吗?

热门文章

  1. gta5卡win键的解决方案汇总
  2. 计算机网络英语的参考文献,计算机网络英语学论文参考文献 哪里有计算机网络英语参考文献...
  3. 华为手机的备忘录内容如何导出到OPPO手机?
  4. Python类的定义和使用
  5. 齐鲁工大青年论坛“体感与移动应用开发”举办
  6. selenium 判断某一个提交操作是否成功的方法
  7. Android悬浮窗各版本系统适配方案
  8. 报错: Err:8 http://mirrors.tuna.tsinghua.edu.cn/ros/ubuntu xenial Release.gpg The following signatur
  9. 聊聊互联网巨头在新加坡的职位与薪酬
  10. UGUI背包实现详解之一UGUI精准拖拽