springboot @JsonSerialize的使用讲解

目录
  • @JsonSerialize的使用讲解
    • 1.写一个类继承JsonSerializer 抽象类
    • 2.然后在传输的实体类中的属性上
    • 3.附加:还有一个比较好用的注解
    • 4.附加:之前附件3的注解,还是有个问题
  • @JsonSerialize 相关使用(jsonUtil)
    • 基础注解使用
    • 框架层面的使用
    • 附:jsonUtil完整代码

@JsonSerialize的使用讲解

解决前端显示和后台存储数据单位不一致的问题。

在返回对象时,进行自定义数据格式转换。

1.写一个类继承JsonSerializer 抽象类

实现其serialize()方法,然后在方法中写入转换规则即可

举例是把Date时间戳从 毫秒 转换成 秒 为单位

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.util.Date;

/**
 * @program: sell
 * @description: 时间转换Json序列化工具
 * @author: Liang Shan
 * @create: 2019-08-06 16:58
 **/
public class Date2LongSerializer extends JsonSerializer<Date> {
    @Override
    public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeNumber(date.getTime() / 1000);
    }
}

2.然后在传输的实体类中的属性上

打上@JsonSerialize注解即可

import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.ls.sell.enums.OrderStatusEnum;
import com.ls.sell.enums.PayStatusEnum;
import com.ls.sell.util.serializer.Date2LongSerializer;
import lombok.Data;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.math.BigDecimal;
import java.util.Date;

/**
 * @program: sell
 * @description: 订单主表
 * @author: Liang Shan
 * @create: 2019-07-24 09:44
 **/
@Entity
@Data
@DynamicUpdate
public class OrderMaster {
    @Id
    private String orderId;
    private String buyerName;
    private String buyerPhone;
    private String buyerAddress;
    private String buyerOpenid;
    private BigDecimal orderAmount;

    /** 订单状态,默认为新下单. */
    private Integer orderStatus = OrderStatusEnum.NEW.getCode();
    /** 支付状态,默认为0未支付. */
    private Integer payStatus = PayStatusEnum.WAIT.getCode();
    @JsonSerialize(using = Date2LongSerializer.class)
    private Date createTime;
    @JsonSerialize(using = Date2LongSerializer.class)
    private Date updateTime;
}

3.附加:还有一个比较好用的注解

如果返回对象中变量存在null,可以使用@JsonInclude(JsonInclude.Include.NON_NULL)注解来忽略为null的变量,这样前端比较好处理

package com.ls.sell.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.ls.sell.entity.OrderDetail;
import com.ls.sell.entity.OrderMaster;
import lombok.Data;
import java.util.List;

/**
 * @program: sell
 * @description: 数据传输对象,传给前端时忽略值为null的属性
 * @author: Liang Shan
 * @create: 2019-07-25 16:05
 **/
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class OrderDTO extends OrderMaster {
    private List<OrderDetail> orderDetailList;
}

使用注解之前的返回值:

使用注解之后:

还是比较好用的。

4.附加:之前附件3的注解,还是有个问题

如果一个一个实体类配置的话,未免太过麻烦,所以可以在配置文件中直接配置,yml配置文件如下:

@JsonSerialize 相关使用(jsonUtil)

基础注解使用

1、实现JsonSerializer接口

例:

public class MySerializerUtils extends JsonSerializer<Integer> {
    @Override
    public void serialize(Integer status, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
        String statusStr = "";
         switch (status) {
             case 0:
                 statusStr = "新建状态";
                 break;
                 }
                 jsonGenerator.writeString(statusStr);
     }
 }

2、添加注解

注:@JsonSerialize注解,主要应用于数据转换,该注解作用在该属性的getter()方法上。

①用在属性上(自定义的例子)

@JsonSerialize(using = MySerializerUtils.class)
private int status;

②用在属性上(jackson自带的用法)

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonDeserialize(using = LocalDateTimeDeserializer.class)
    @JsonSerialize(using = LocalDateTimeSerializer.class)
private LocalDateTime sendTime;

③用在空对象上可以转化

@JsonSerialize
public class XxxxxBody {
 // 该对象暂无字段,直接new了返回
}

框架层面的使用

jsonUtil工具类

实现json转换时所有的null转为“”

1、实现JsonSerializer类

public class CustomizeNullJsonSerializer {
    public static class NullStringJsonSerializer extends JsonSerializer<Object> {
        @Override
        public void serialize(Object value, JsonGenerator jsonGenerator,
                              SerializerProvider serializerProvider) throws IOException {
            jsonGenerator.writeString("");
        }
    }
}

2、实现BeanSerializerModifier类

public class CustomizeBeanSerializerModifier extends BeanSerializerModifier {
    @Override
    public List<BeanPropertyWriter> changeProperties(SerializationConfig config,
                                                     BeanDescription beanDesc,
                                                     List<BeanPropertyWriter> beanProperties) {
        for (int i = 0; i < beanProperties.size(); i++) {
            BeanPropertyWriter writer = beanProperties.get(i);
            if (isStringType(writer)) {
                writer.assignNullSerializer(new CustomizeNullJsonSerializer.NullStringJsonSerializer());
            }
        }
        return beanProperties;
    }
    /**
     * 是否是String
     */
    private boolean isStringType(BeanPropertyWriter writer) {
        Class<?> clazz = writer.getType().getRawClass();
        return CharSequence.class.isAssignableFrom(clazz) || Character.class.isAssignableFrom(clazz);
    }
}

3、工具类调用

public class JsonUtil {
//序列化时String 为null时变成""
    private static ObjectMapper mapperContainEmpty = new ObjectMapper();
static {
        mapperContainEmpty.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        mapperContainEmpty.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapperContainEmpty.setSerializerFactory(mapperContainEmpty.getSerializerFactory()
                .withSerializerModifier(new CustomizeBeanSerializerModifier()));
    }
 /**
     * 将对象转换为Json串,针对String 类型 null 转成""
     */
    public static String toJsonContainEmpty(Object o) {
        try {
            return mapperContainEmpty.writeValueAsString(o);
        } catch (IOException e) {
            logger.error("render object to json error: {}", e.getMessage(), e);
            throw new RuntimeException("render object to json error!", e);
        }
    }
}

附:jsonUtil完整代码

/**
 * json串和对象之间相互转换工具类
 */
public class JsonUtil {
    private static Logger logger = LoggerFactory.getLogger(JsonUtil.class);
    private static ObjectMapper mapper = new ObjectMapper();
    //序列化时String 为null时变成""
    private static ObjectMapper mapperContainEmpty = new ObjectMapper();
    static {
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setSerializationInclusion(Include.NON_NULL);
        mapperContainEmpty.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        mapperContainEmpty.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapperContainEmpty.setSerializerFactory(mapperContainEmpty.getSerializerFactory()
                .withSerializerModifier(new CustomizeBeanSerializerModifier()));
    }
    /**
     * 将对象转换为Json串
     */
    public static String toJson(Object o) {
        try {
            return mapper.writeValueAsString(o);
        } catch (IOException e) {
            logger.error("render object to json error: {}", e.getMessage(), e);
            throw new RuntimeException("render object to json error!", e);
        }
    }
    /**
     * 将对象转换为Json串,针对String 类型 null 转成""
     */
    public static String toJsonContainEmpty(Object o) {
        try {
            return mapperContainEmpty.writeValueAsString(o);
        } catch (IOException e) {
            logger.error("render object to json error: {}", e.getMessage(), e);
            throw new RuntimeException("render object to json error!", e);
        }
    }
    /**
     * 将Json串转换为对象
     */
    public static <T> T toObject(String json, Class<T> clazz) {
        try {
            return mapper.readValue(json, clazz);
        } catch (IOException e) {
            logger.error("render json to object error: {}", e.getMessage(), e);
            throw new RuntimeException("render json to object error!", e);
        }
    }
    /**
     * 将Json串转换为List
     */
    public static <T> List<T> toList(String json, Class<T> clazz) {
        try {
            JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, clazz);
            return mapper.readValue(json, javaType);
        } catch (IOException e) {
            logger.error("render json to List<T> error: {}", e.getMessage(), e);
            throw new RuntimeException("render json to List<T> error!", e);
        }
    }
    /**
     * 将Json串转换为Map
     */
    public static <K, V> Map<K, V> toMap(String json, Class<K> clazzKey, Class<V> clazzValue) {
        try {
            JavaType javaType = mapper.getTypeFactory().constructParametricType(Map.class, clazzKey, clazzValue);
            return mapper.readValue(json, javaType);
        } catch (IOException e) {
            logger.error("render json to Map<K, V> error: {}", e.getMessage(), e);
            throw new RuntimeException("render json to Map<K, V> error!", e);
        }
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • SpringMVC用JsonSerialize日期转换方法

    最近在用SpringMvc做Http接口时,对方在调用我接口时发现Date格式的默认转化为long,因此在前端页面看到的是一串数字. 我们可以自定义代码的转换器,返回数据到前台的时候就可以按照我们的需要返回格式化后的字符串类型数据. package com.cnpc.mall.web.utils; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import org.cod

  • springboot json时间格式化处理的方法

    application.properties中加入如下代码 springboot 默认使用 jackson 解析 json spring.jackson.date-format=yyyy-MM-dd HH:mm:ss spring.jackson.time-zone=GMT+8 如果个别实体需要使用其他格式的 pattern,在实体上加入注解即可 import org.springframework.format.annotation.DateTimeFormat; import com.fas

  • 详解Springboot之接收json字符串的两种方式

    第一种方式.通过关键字段@RequestBody,标明这个对象接收json字符串.还有第二种方式,直接通过request来获取流.在spring中,推荐使用. 代码地址 https://gitee.com/yellowcong/springboot-demo/tree/master/springboot-json 项目结构 其实项目里面没啥类容,就是一个控制器和pom.xml配置 配置fastjson 添加fastjson的依赖到pom.xml中 <dependency> <groupI

  • Spring Boot使用FastJson解析JSON数据的方法

    个人使用比较习惯的json框架是fastjson,所以spring boot默认的json使用起来就很陌生了,所以很自然我就想我能不能使用fastjson进行json解析呢? 1.引入fastjson依赖库: <!--添加fastjson解析JSON数据--> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <versio

  • springboot @JsonSerialize的使用讲解

    目录 @JsonSerialize的使用讲解 1.写一个类继承JsonSerializer 抽象类 2.然后在传输的实体类中的属性上 3.附加:还有一个比较好用的注解 4.附加:之前附件3的注解,还是有个问题 @JsonSerialize 相关使用(jsonUtil) 基础注解使用 框架层面的使用 附:jsonUtil完整代码 @JsonSerialize的使用讲解 解决前端显示和后台存储数据单位不一致的问题. 在返回对象时,进行自定义数据格式转换. 1.写一个类继承JsonSerializer

  • Springboot与vue实例讲解实现前后端分离的人事管理系统

    目录 一,项目简介 二,环境介绍 三,系统展示 四,核心代码展示 五,项目总结 一,项目简介 系统是前后端分离的项目,直接启动Springboot应用程序类后,再启动前端工程访问即可.主要实现了企业的人事管理功能,主要包含员工管理.薪资管理.职位管理.权限管理.网盘文件分享管理等模块. 系统亮点:使用REDIS进行数据缓存,优化查询性能:使用分布式文件系统进行文件存储服务:基于Springboot+vue实现前后端分离开发 二,环境介绍 语言环境:Java: jdk1.8 数据库:Mysql:

  • SpringBoot使用Swagger范例讲解

    目录 1. Swagger 介绍 2. 使用Swagger接口文档框架 1. Swagger 介绍 在一个项目开发过程中,当前端开发人员根据后端开发人员给出的 API 接口文档进行接口联调对接时,可能会出现这样的矛盾:前端开发人员抱怨后端开发人员给出的 API 接口文档和实际的情况有所出入,而后端开发人员由于繁重的开发任务已经身心俱疲,想到自己还要负责维护接口文档的任务更是不堪重负. 这时就需要一个解决方案,希望它能够在后端开发人员进行接口开发时,能够帮助后端工程师自动生成相应的接口文档,当接口

  • SpringBoot超详细深入讲解底层原理

    目录 手写springboot Springboot项目 自动配置 小结 手写springboot 在日常开发中只需要引入下面的依赖就可以开发Servlet进行访问了. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> 那这是怎么做到的呢?今天就来

  • Springboot启动原理详细讲解

    主启动类方法: @SpringBootApplication public class MyJavaTestApplication { public static void main(String[] args) { SpringApplication.run(MyJavaTestApplication.class, args); } } 点击进入方法 public static ConfigurableApplicationContext run(Class<?>[] primarySour

  • SpringBoot整合freemarker的讲解

    freemarker和thymeleaf是模板引擎.在早前我们使用Struts或者SpringMVC等框架的时候,使用的都是jsp,jsp的本质其实就是一个Servlet,其中的数据需要在后端进行渲染,然后再在客户端显示,效率比较低下.而模板引擎恰恰相反,其中的数据渲染是在客户端,效率方面比较理想一点.前后端不分离的话用模板引擎比较好,前后端分离的话其实用处并不大很大.Spring官方比较推荐的是thymeleaf,其文件后缀是html.本篇文章我们主要来看看SpringBoot整合freema

  • springboot常用注释的讲解

    1:@Qualifier @Qualifier 注释指定注入 Bean 的名称,这样歧义就消除了.所以@Autowired 和@Qualifier 结合使用时,自动注入的策略就从 byType 转变成 byName 了.例子如下: 有一个接口: public interface EmployeeService { public String getEmployeeById(Long id); } 有两个实现类: @Service("service") public class Empl

  • SpringBoot Admin用法实例讲解

    说明 Spring Boot Admin 是一个管理和监控你的 Spring Boot 应用程序的应用程序. 这些应用程序通过 Spring Boot Admin Client(通过 HTTP)注册或者使用 Spring Cloud(例如 Eureka)发现. UI只是 Spring Boot Actuator 端点上的一个 AngularJs 应用程序. 创建服务 创建spring boot 项目,引入依赖 <dependency> <groupId>de.codecentric

  • SpringBoot集成kafka全面实战记录

    本文是SpringBoot+Kafka的实战讲解,如果对kafka的架构原理还不了解的读者,建议先看一下<大白话kafka架构原理>.<秒懂kafka HA(高可用)>两篇文章. 一.生产者实践 普通生产者 带回调的生产者 自定义分区器 kafka事务提交 二.消费者实践 简单消费 指定topic.partition.offset消费 批量消费 监听异常处理器 消息过滤器 消息转发 定时启动/停止监听器 一.前戏 1.在项目中连接kafka,因为是外网,首先要开放kafka配置文件

  • Spring中SmartLifecycle和Lifecycle的作用和区别

    本文基于SpringBoot 2.5.0-M2讲解Spring中Lifecycle和SmartLifecycle的作用和区别,以及如何控制SmartLifecycle的优先级. 并讲解SpringBoot中如何通过SmartLifecycle来启动/停止web容器. SmartLifecycle和Lifecycle作用 都是让开发者可以在所有的bean都创建完成(getBean) 之后执行自己的初始化工作,或者在退出时执行资源销毁工作. SmartLifecycle和Lifecycle区别 1.

随机推荐