springboot Jackson 个性化序列化操作

文章目录

自定义类型序列化反序列化器

  1. 添加个性化操作类
public class RecordDeserializer extends JsonDeserializer<Record> {

    public String convert(String key) {

        String propertyName = key;
        String property;
        String alias = null;

        if (propertyName.contains(".")) {
            String[] properties = propertyName.split("\\.");
            alias = properties[0];
            property = properties[1];
        } else {
            property = propertyName;
        }

        StringBuilder buf = new StringBuilder(property);
        for (int i = 1; i < buf.length() - 1; i++) {
            if (Character.isLowerCase(buf.charAt(i - 1)) && Character.isUpperCase(buf.charAt(i)) && Character.isLowerCase(buf.charAt(i + 1))) {
                buf.insert(i++, '_');
            }
        }
        return (alias != null ? alias + "." : "") + buf.toString().toLowerCase();

    }

    @Override
    public Record deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        Map<String, Object> map = jsonParser.readValueAs(new TypeReference<Map<String, Object>>() {
        });

        Map<String, Object> deserializeMap = new HashMap<>();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            deserializeMap.put(convert(entry.getKey()), entry.getValue());
        }
        Record record = new Record().setColumns(deserializeMap);
        return record;
    }
}
public class RecordSerializer extends JsonSerializer<Record> {
    private static Pattern linePattern = Pattern.compile("_(\\w)");

    /**
     * 下划线转驼峰
     *
     * @param key record 的key
     * @return 转换后的key
     */
    public String convert(String key) {
        String property;
        String alias = null;

        if (key.contains(".")) {
            String[] properties = key.split("\\.");
            alias = properties[0];
            property = properties[1];
        } else {
            property = key;
        }

        String str = property.toLowerCase();
        Matcher matcher = linePattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return (alias != null ? alias + "." : "") + sb.toString();
    }


    @Override
    public void serialize(Record record, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (record != null) {
            Map<String, Object> columnMap = record.getColumns();

            Map<String, Object> serializerMap = new HashMap<>();
            for (Map.Entry<String, Object> entry : columnMap.entrySet()) {
                serializerMap.put(convert(entry.getKey()), entry.getValue());
            }

            serializerProvider.defaultSerializeValue(serializerMap, jsonGenerator);
        }
    }


}
  1. 添加 AutoConfiguration 类
@Configuration(proxyBeanMethods = false)
@AutoConfigureAfter({JacksonAutoConfiguration.class})
@ConditionalOnClass({ObjectMapper.class})
public class DataAccessJacksonAutoConfiguration {

    /**
     * 自己添加的序列化类,在配置中添加模型映射
     *
     * @param objectMapper jackson
     */
    MJacksonAutoConfiguration(ObjectMapper objectMapper) {
        SimpleModule module = new SimpleModule("MRecordModule");
        module.addSerializer(Model.class, new RecordSerializer());
        module.addDeserializer(Model.class, new RecordDeserializer<>());
        objectMapper.registerModule(module);
    }
}

指定使用某一个序列化器的类

  1. 添加 SimpleDeserializers 实现类
public class RecordSimpleDeserializers extends SimpleDeserializers {
    @Override
    public JsonDeserializer<?> findBeanDeserializer(JavaType type, DeserializationConfig config, BeanDescription beanDesc) throws JsonMappingException {
        if(type.getSuperClass() != null && type.getSuperClass().getRawClass().equals(Model.class)){
            if (_classMappings == null) {
                return null;
            }
            return _classMappings.get(new ClassKey(Model.class));
        }
        return super.findBeanDeserializer(type, config, beanDesc);
    }
}
  1. 将实现类进行注册
	module.setDeserializers(new RecordSimpleDeserializers());
上一篇:用户密码加解密(数据库层面)


下一篇:Oracle的ORA-02292报错:违反完整性约束,已找到子记录