設定Springboot返回jackson資料序列化

FH-Admin發表於2021-08-25

LocalDateTime格式化
使用下面的配置相當於全域性配置就不需要給欄位新增@JsonFormat(pattern = DateUt.YYYY_MM_DD_HH_MM_SS)
如果個別欄位需要不同的配置可使用@JsonFormat(pattern = DateUt.YYYY_MM_DD),@JsonFormat會優先使用,反序列化亦可使用@JsonFormat註解

package com.example.mpdemo.config;

import com.example.mpdemo.common.IBaseEnum;
import com.example.mpdemo.util.DateUt;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import org.springframework.boot.jackson.JsonComponentModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

/**
 * @from: fhadmin.cn
 * @Date: 2021/8/19
 * @Description: 時間統一格式化
 */
@Configuration
public class JSONFormatConfig {

    private static final DateTimeFormatter ymdhms = DateTimeFormatter.ofPattern(DateUt.YYYY_MM_DD_HH_MM_SS);

    private static final DateTimeFormatter ymd = DateTimeFormatter.ofPattern(DateUt.YYYY_MM_DD);

    private static final DateTimeFormatter hms = DateTimeFormatter.ofPattern(DateUt.HH_MM_SS);

    @Bean
    @Primary
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        //序列化設定時間格式
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(ymdhms));
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(ymd));
        javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(hms));
        //反序列化設定時間格式
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(ymdhms));
        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(ymd));
        javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(hms));

        objectMapper.registerModule(javaTimeModule);
        //序列化列舉值為資料庫儲存值 缺少後列印列舉不能轉成對應值,需自定義toString方法/或者使用@JsonValue註解
        //objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
        //設定序列化列舉格式
        JsonComponentModule jsonComponentModule = new JsonComponentModule();
        jsonComponentModule.addSerializer(IBaseEnum.class,new BaseEnumSerializer());
        objectMapper.registerModule(jsonComponentModule);
        return objectMapper;
    }
}
#Date型別生效
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8

把下面的類註冊在objectMapper中

//設定序列化列舉格式
JsonComponentModule jsonComponentModule = new JsonComponentModule();
jsonComponentModule.addSerializer(IBaseEnum.class,new BaseEnumSerializer());
objectMapper.registerModule(jsonComponentModule);

根據業務需求調整需要格式化的結構

package com.example.mpdemo.config;

import com.example.mpdemo.common.IBaseEnum;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import org.springframework.boot.jackson.JsonComponent;

import java.io.IOException;

/**
 * @from: fhadmin.cn
 * @Date: 2021/8/19
 * @Description: 組織型別列舉序列化
 */

//可以使用JsonSerializer
public class BaseEnumSerializer extends JsonSerializer<IBaseEnum> {
//public class BaseEnumSerializer extends StdSerializer<IBaseEnum> {

    //protected BaseEnumSerializer(){
    //    super(IBaseEnum.class);
    //}

    @Override
    public void serialize(IBaseEnum value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        //返回列舉物件值字串
        //gen.writeString(value.getValue().toString());
        //返回列舉物件值
        gen.writeObject(value.getValue());
        //enum2Object(value, gen);
    }

    /**
     * 把列舉轉成物件
     */
    private void enum2Object(IBaseEnum value, JsonGenerator gen) throws IOException {
        gen.writeStartObject();
        gen.writeFieldName(IBaseEnum.ID);
        gen.writeObject(value.getValue());
        gen.writeFieldName(IBaseEnum.NAME);
        gen.writeString(value.getName());
        gen.writeEndObject();
    }
}

使用@JsonValue註解加在需要序列化的欄位上,可省略註冊配置,只能顯示對應的值,不可擴充套件,如需要擴充套件使用@JsonSerialize(using = BaseEnumSerializer.class)註解

package com.example.mpdemo.enums;

import com.example.mpdemo.common.IBaseEnum;
import com.example.mpdemo.config.BaseEnumSerializer;
import com.fasterxml.jackson.annotation.JsonValue;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

/**
 * @from: fhadmin.cn
 * @Date: 2021/8/17
 * @Description: 是否刪除
 */
//不使用全域性配置可使用該註解
//@JsonSerialize(using = BaseEnumSerializer.class)
public enum DeleteEnum implements IBaseEnum<Boolean> {

    DELETE_YES(true,"已刪除"),
    DELETE_NO(false,"未刪除");

    //使用JsonValue註解可格式化顯示值
    @JsonValue
    private final boolean id;
    private final String name;

    DeleteEnum(boolean id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public Boolean getValue() {
        return this.id;
    }

    @Override
    public String getName() {
        return this.name;
    }

    //使用JsonValue註解可註釋掉toString
    /*@Override
    public String toString() {
        //根據情況給前臺資料展示deleted或descp
        return String.valueOf(this.deleted);
    }*/
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章