需求是把对象的子对象(枚举类型)同时序列化为JSON字符串
如果只是使用SONObject.toJSONString(data),只会把枚举对象的值序列化
所以需要配置定义枚举序列化器
方法的第一个参数和JsonSerializer<泛型>为目标泛型对象
package com.evking.cppwebbackend.common.config;
import com.evking.cppwebbackend.common.enums.general.CommonEnum;
import com.evking.cppwebbackend.common.enums.pile.ApplyStatusEnum;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
/**
*
* @author yangfuheng
* @date 2024/08/09 15:04
* @description 通用枚举序列化器,需要在目标枚举对象加上@JsonSerialize(using = CommonEnumSerializer.class)
* 在序列化时,将枚举的name、code、desc字段输出
*
*/
public class CommonEnumSerializer extends JsonSerializer<ApplyStatusEnum> {
@Override
public void serialize(ApplyStatusEnum commonEnum, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField("name", commonEnum.name());
gen.writeStringField("code", String.valueOf(commonEnum.getCode()));
gen.writeStringField("desc", commonEnum.getDesc());
gen.writeEndObject();
}
}
接着在子枚举对象加上
@JsonSerialize(using = CommonEnumSerializer.class)
package com.evking.cppwebbackend.common.enums.pile;
import com.baomidou.mybatisplus.annotation.EnumValue;
import com.evking.cppwebbackend.common.enums.general.CommonEnum;
import com.evking.cppwebbackend.common.config.CommonEnumSerializer;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* @author zhongcm
* @title ApplyStatusEnum
* @description
* @date 2024/4/21 6:27
*/
@Getter
@AllArgsConstructor
@JsonSerialize(using = CommonEnumSerializer.class)
public enum ApplyStatusEnum implements CommonEnum {
/**
* 状态(0-未确认,1-已确认)
*/
UNCONFIRMED(0, "待确认"),
CONFIRMED(1, "已确认"),
;
@EnumValue
private final Integer code;
private final String desc;
}
最后使用
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(data);
即可完成。