欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

springboot @JsonSerialize的使用讲解

程序员文章站 2022-06-24 21:09:42
目录@jsonserialize的使用讲解1.写一个类继承jsonserializer 抽象类@jsonserialize 相关使用(jsonutil)附:jsonutil完整代码@jsonseria...

@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;
}

使用注解之前的返回值:

springboot @JsonSerialize的使用讲解

使用注解之后:

springboot @JsonSerialize的使用讲解

还是比较好用的。

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

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

springboot @JsonSerialize的使用讲解

@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);
        }
    }
}

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