jackson自定义序列化将枚举处理成平行结构

1.背景

  • 项目中后端要把枚举类型传给前端,但是前端要用枚举的code和desc,且这两个字段要跟主类平行结构。我这么说大家可能不太理解,下面上代码
    实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private long id;
    private TaskStatus taskStatus;
}

枚举类

@Getter
@AllArgsConstructor
public enum TaskStatus implements IEnum {


    /**
     * 任务状态
     */
    UNPUBLISHED("unpublished", "待发布"),
    PUBLISHED("published", "发布"),
    PROCESSING("processing", "进行中"),
    AHEAD_COMPLETED("ahead_completed", "提前完成"),
    COMPLETED("completed", "已完成"),
    OVERDUE("overdue", "已超期"),
    ;

    /**
     * 成员变量
     */
    private final String code;
    private final String desc;


    public static TaskStatus getByCode(String code) {
        for (TaskStatus status : TaskStatus.values()) {
            if (status.code.equals(code)) {
                return status;
            }
        }
        return null;
    }

    public static TaskStatus getByDesc(String desc) {
        for (TaskStatus status : TaskStatus.values()) {
            if (status.desc.equals(desc)) {
                return status;
            }
        }
        return null;
    }
}

枚举接口类

public interface IEnum {

    T getCode();

    T getDesc();


}
  • 起初用的fastjson,但是fastjson不支持细粒度控制,所以换jackson,jackson可以更细粒度的控制bean的序列化。
  • 我的思路是通过IEnum接口来识别需要自定义序列化的枚举变量,然后调用自定义序列化方法进行序列化数据。
    照着网上的例子编写了如下自定义序列化实现
public class EnumsCodec extends JsonSerializer {


    @Override
    public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {

        String className = o.getClass().getSimpleName();
        char[] cs = className.toCharArray();
        cs[0] = toLowerCase(cs[0]);
        className = String.valueOf(cs);
        
        jsonGenerator.writeStringField(className, o.toString());
        jsonGenerator.writeStringField(className + "Desc", ((IEnum) o).getDesc());


    }

    public char toUpperCase(char chars) {
        if (97 <= chars && chars <= 122) {
            chars -= 32;
        }
        return chars;
    }

    public char toLowerCase(char chars) {
        if (65 <= chars && chars <= 90) {
            chars += 32;
        }
        return chars;
    }
}

JsonUtil类如下

@Slf4j
public class JsonUtil {

    private static final ObjectMapper mapper = new ObjectMapper();

    static {
        mapper.findAndRegisterModules();
        SimpleModule simpleModule = new SimpleModule();
        //注册一个统一的枚举序列方法,实现IEnum接口的枚举序列化时取desc字段
        simpleModule.addSerializer(IEnum.class, new EnumsCodec());
        mapper.registerModule(simpleModule);

    }


    private JsonUtil() {
    }

    /**
     * json serialization.
     *
     * @param obj 要进行序列化的对象
     * @return 返回序列化之后的字符串
     */
    public static String dumps(Object obj) {
        try {
            String result = mapper.writeValueAsString(obj);
            return result;
        } catch (JsonProcessingException ex) {
            log.error("failed serialize object to json string: {}", ex);
        }
        return null;
    }

    /**
     * json deserialization.
     *
     * @param jsonStr 序列化字符串
     * @param cls     指定反序列化之后的类信息
     * @return 返回反序列化之后的实例对象
     */
    public static  T loads(String jsonStr, Class cls) {
        T object = null;
        try {
            object = mapper.readValue(jsonStr, cls);
        } catch (IOException ex) {
            log.error("failed deserialize string: {} to Class {}'s instance, error: {}", jsonStr,
                    cls.getName(), ex);
        }
        return object;
    }

    /**
     * json deserialization.
     *
     * @param jsonStr      序列化字符串
     * @param valueTypeRef 指定反序列化之后的类信息
     * @return 返回反序列化之后的实例对象
     */
    public static  T loads(String jsonStr, TypeReference valueTypeRef) {
        T object = null;
        try {
            object = mapper.readValue(jsonStr, valueTypeRef);
        } catch (IOException ex) {
            log.error("failed deserialize string: {} to Class {}'s instance, error: {}", jsonStr,
                    valueTypeRef.getClass().getName(), ex);
        }
        return object;
    }

    public static  T loads(InputStream inputStream, Class cls) {
        T obj = null;
        try {
            obj = mapper.readValue(inputStream, cls);
        } catch (JsonParseException e) {
            log.error("JsonUtil:jjson转换异常!", e);
        } catch (JsonMappingException e) {
            log.error("JsonUtil:json映射异常", e);
        } catch (IOException e) {
            log.error("JsonUtil:json转换异常", e);
        }
        return obj;
    }


    public static JsonNode jsonNode(String jsonStr) {
        try {
            return mapper.readTree(jsonStr);
        } catch (IOException ex) {
            log.error("failed deserialize string: {} to JsonNode, error: {}", jsonStr, ex);
        }
        return null;
    }

    public static void main(String[] args) throws IOException {


        User user = new User();

        user.setId(1);
        user.setTaskStatus(TaskStatus.COMPLETED);
        String str = mapper.writeValueAsString(user);
        System.out.println(str);

        String str1 = "{\"id\":1,\"taskStatus\":\"COMPLETED\"}";

        User user1 = mapper.readValue(str1, User.class);

        System.out.println(user1.getTaskStatus());
    }

}

运行后报错如下:

Exception in thread "main" com.fasterxml.jackson.core.JsonGenerationException: Can not write a field name, expecting a value
    at com.fasterxml.jackson.core.JsonGenerator._reportError(JsonGenerator.java:1676)
    at com.fasterxml.jackson.core.json.WriterBasedJsonGenerator.writeFieldName(WriterBasedJsonGenerator.java:109)
    at com.fasterxml.jackson.core.json.JsonGeneratorImpl.writeStringField(JsonGeneratorImpl.java:202)
    at com.***.jsoncodec.EnumsCodec.serialize(EnumsCodec.java:25)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:672)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:678)
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:157)
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:130)
    at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:3631)
    at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:2998)
    at com.***.util.JsonUtil.main(JsonUtil.java:119)

百思不得解,经过各种实验,发现在2.3版本可以,2.7版本不行,但是我们项目强依赖2.7版本,这怎么办呢。。。。。。

google了一遍,照着网上的方法把修改如下

@Override
    public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {

        String className = o.getClass().getSimpleName();
        char[] cs = className.toCharArray();
        cs[0] = toLowerCase(cs[0]);
        className = String.valueOf(cs);
       
        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField(className, o.toString());
        jsonGenerator.writeStringField(className + "Desc", ((IEnum) o).getDesc());
        jsonGenerator.writeEndObject();

    }

运行结果如下

{"id":1,"taskStatus":{"taskStatus":"COMPLETED","taskStatusDesc":"已完成"}}

这个结果不是我想要的呀。
无比愁畅。。。。。。
折腾了一天,还是没找办法,我已经放弃。找前端说搞不出来。
这个时候,群里的一位大神的一句话提醒了我,他说Can not write a field name, expecting a value这个报错可能是新版本做了完整性检查了,于是跟了一下源码,发现2.7版本在序列化时候,key是固定好的,不能直接写入field。那我是不是先给他写一个值,然后再写入一个field的就可以了呢?于是动手试了一下,改造如下

@Override
    public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {

        String className = o.getClass().getSimpleName();
        char[] cs = className.toCharArray();
        cs[0] = toLowerCase(cs[0]);
        className = String.valueOf(cs);
        jsonGenerator.writeString(o.toString());
        jsonGenerator.writeStringField(className + "Desc", ((IEnum) o).getDesc());

    }

运行结果如下

{"id":1,"taskStatus":"COMPLETED","taskStatusDesc":"已完成"}

完美,问题到此解决了。
所以说,有时候你跟真相只差一步之遥,就缺大神指点。

你可能感兴趣的:(jackson自定义序列化将枚举处理成平行结构)