springboot~将一个Integer类型序列为k/v对象

对于一些带着固定标签的字段来说,我们通常把它们配置到字段中,而在数据库中存它们的字典code,或者是字典主键,不是一个整型的数字,而在前端显示时,有时需要将它们翻译成名称,这时后端可以帮他们进行翻译,或者前端通过code自己使用字典翻译;下面说一下第一种,后端在View model中将integer类型的字典字典翻译成一个k/v的对象。

JsonSerializer

一个json序列化的基类,我们可以继承它,并实现自己的原因,在springboot框架中,你返回的json对象事实上是jackson帮我们做了一次序列化工作,而我们的字段如果希望在序列化时行加工,可以利用这个环节,下面定义一下DictionarySerializer,来实现字典字段的序列化。

/**
 * 自定义序列化器,将一个Integer类型的字段序列化成一个name/code的对象
 */
public class DictionarySerializer extends JsonSerializer<Integer> {
    @Autowired
    DictionaryMapper dictionaryMapper;

    @Override
    public void serialize(Integer value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        //获取当前字段的名称
        String type = jsonGenerator.getOutputContext().getCurrentName();
        Integer code = (Integer) value;
        jsonGenerator.writeStartObject();
        Dictionary dictionary = dictionaryMapper.selectOne(
                new QueryWrapper<Dictionary>().lambda()
                        .eq(Dictionary::getCode, code)
                        .eq(Dictionary::getType, type));
        if (dictionary == null)
            throw new IllegalArgumentException(String.format("字典数据未配置,类型:%s,值:%s", type, code));

        jsonGenerator.writeStringField("name", dictionary.getName());
        jsonGenerator.writeNumberField("code", code);
        jsonGenerator.writeEndObject();

    }
}

在实体中gender字段会进行声明

   @ApiModelProperty("性别")
   @JsonSerialize(using= DictionarySerializer.class)
   private Integer gender;
 

在接口中返回一个对象,对象中包含了gender字段,而这个字段已经被序列化成对象,本例通过查询数据库实现,实际工作中,应该通过缓存来实现。

 {
                "id": "ab9a48d4f49d93237f7090d340d9fa07",
                "username": "123",
                "email": "123@qq.com",
                "phone": "13754911028",
                "realName": null,
                "roleList": [
                    {
                        "id": "1",
                        "name": "管理员1"
                    }
                ],
                "createTime": "2022-04-12T10:04:14",
                "updateTime": "2022-04-12T10:04:14",
                "createBy": "admin",
                "updateBy": "admin",
                "status": 1,
                "organization": null,
                "job": null,
                "gender": {
                    "name": "男",
                    "value": 0
                }
            }
posted @ 2022-04-18 21:28  张占岭  阅读(305)  评论(0编辑  收藏  举报