Spring boot jackson于枚举序列化,反序列化的探索

项目中不用枚举是不行的,因为Spring boot默认使用jsckjson执行序列化于反序列化,所以对jackson添加操作,即可使得Spring boot请求周期均有该特性。

一、使用

1.定义枚举

合理使用@JsonCreator、@JsonValue 特性即可实现

package cn.com.iios.demo.enums;
import cn.com.iios.common.exception.EnumParseException;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import lombok.SneakyThrows;

import java.util.HashMap;
import java.util.Map;

public enum UserPosition{
    ADMIN(2,"普通用户"),
    NOTADMIN(3,"管理员");

    private Integer id;
    private String name;
    UserPosition(Integer id,String name){
        this.id = id;
        this.name = name;
    }
    public Integer getId(){
        return this.id;
    }
    public String getName(){
        return this.name;
    }

    /**
     * 根据ID,返回实例
     * @param id
     * @return
     * @throws Exception
     */
    @JsonCreator
    @SneakyThrows
    public static UserPosition getById(Integer id){
        for(UserPosition singleEnum:UserPosition.values()){
            if(singleEnum.getId()==id){
                return singleEnum;
            }
        }
        throw new EnumParseException(UserPosition.class,id);
    }
    @JsonValue
    public Map<Integer,String> toJson(){
        Map map = new HashMap<Integer,String>();
        map.put("id",getId());
        map.put("name",getName());
        return map;
    }
}

2. 与Spring Data JPA结合

package cn.com.iios.demo.entity;

import cn.com.iios.common.entity.BaseEntity;
import cn.com.iios.demo.enums.UserPosition;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import lombok.SneakyThrows;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;

import javax.persistence.*;

@Data
@Entity
@Table(name = "user")
@Where(clause = "is_deleted != 1")
@SQLDelete(sql = "update user set is_deleted = 1 where id = ?")
public class User extends BaseEntity {



    private String name;

    public String getName(){
        return name;
    }
    @Column(name="login_name")
    private String loginName;

    private String password;

    private String uuid;

    @Column(name="is_company_account")
    private Boolean isCompanyAccount;

    @Column(name="id_number")
    private String idNumber;


    @Column(name="is_admin")
    private Integer isAdminOriginal;

    @Transient
    private UserPosition isAdmin;

    @SneakyThrows
    // 枚举项不能为空
    public UserPosition getIsAdmin(){

        // 用于Data JPA -> Service
        if(isAdmin==null && isAdminOriginal!=null){
            return UserPosition.getById(this.isAdminOriginal);
        }
        // 用于Restful -> Service
        if(isAdmin!=null && isAdminOriginal == null){
            return isAdmin;
        }
        // 其它状态均为空或不存在(不存在都成立的情况)
        return null;
    }

}

 

分享到:更多 ()