上一篇:[Jackson自定义序列化注解(1)- Map的key驼峰蛇形的转换]中,实现了对Map的key的参数转换,但是总是存在一些骚操作:
如上图所示,这样对象Y就可以动态的选择序列化的字段。
本文主要实现Map对象(A,B)如何扁平化到Bean中?且扁平化的过程中,需要完成驼峰->蛇形的转换。
注:借鉴@JsonProperty的实现思路。
实现代码
引入依赖:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.0.1-jre</version>
</dependency>
自定义注解:
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface DynamicCaseFormatFields {
CaseFormat sourceFormat() default CaseFormat.LOWER_CAMEL;
CaseFormat format() default CaseFormat.LOWER_CAMEL;
boolean withNumber() default false;
}
public class DynamicCaseFormatFieldsBeanSerializerModifier extends BeanSerializerModifier {
@Override
public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc,
List<BeanPropertyWriter> beanProperties) {
return beanProperties.stream().map(bpw -> {
DynamicCaseFormatFields
annotation = bpw.getAnnotation(DynamicCaseFormatFields.class);