Jackson 进阶之自定义序列化器

Jackson 的基本介绍可以参考 Jackson 使用简介

JsonSerializer 的简单使用

1)实现 JsonSerializer 接口

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;

public class ObfuscatedIdSerializer extends JsonSerializer {
    @Override
    public void serialize(Integer value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value == null) {
            gen.writeNull();
        } else if (value == 1) {
            gen.writeString("字符串 1");
        } else {
            gen.writeNumber(value);
        }
    }
}

2)定义需要序列化的类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
    private String name;

    @JsonSerialize(using = ObfuscatedIdSerializer.class)
    private int age;

    private int anotherAge;

    public static Person from(String name, int age) {
        return new Person(name, age, age);
    }
}

@JsonSerializer 注解的作用是声明使用自定义的序列化类(实现了 JsonSerializer 接口)

3)进行序列化操作

public class JacksonDemo1 {

    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.writeValueAsString(Person.from("zhangsan", 18)));
        System.out.println(mapper.writeValueAsString(Person.from("zhangsan", 1)));
    }
}

控制台输出:

{"name":"zhangsan","age":18,"anotherAge":18}
{"name":"zhangsan","age":"字符串 1","anotherAge":1}

JsonDeserializer 的简单使用

1)实现 JsonDeserializer 接口

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

import java.io.IOException;

public class ObfuscatedIdDeserializer extends JsonDeserializer {

    @Override
    public Integer deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        String obfuscatedId = p.getText().trim();
        if (obfuscatedId.isEmpty()) {
            return null;
        }

        if (obfuscatedId.equals("字符串 1")) {
            return 1;
        }

        return Integer.valueOf(obfuscatedId);
    }
}

2)定义需要序列化的类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
    private String name;

    @JsonSerialize(using = ObfuscatedIdSerializer.class)
    @JsonDeserialize(using = ObfuscatedIdDeserializer.class)
    private int age;

    private int anotherAge;

    public static Person from(String name, int age) {
        return new Person(name, age, age);
    }
}

@JsonDeserialize 注解的作用是声明使用自定义的反序列化类(实现了 JsonDeserializer 接口)

3)进行序列化操作

public class JacksonDemo2 {
     private static ObjectMapper mapper = new ObjectMapper();

    public static void main(String[] args) throws IOException {
        serializerAndDeserializer(Person.from("zhangsan", 18));
        serializerAndDeserializer(Person.from("zhangsan", 1));
    }

    private static void serializerAndDeserializer(Person person) throws IOException {

        String serializer = mapper.writeValueAsString(person);
        Person deserializer = mapper.readValue(serializer, Person.class);

        System.out.println(serializer);
        System.out.println(deserializer);
    }
}

控制台输出:

{"name":"zhangsan","age":18,"anotherAge":18}
Person(name=zhangsan, age=18, anotherAge=18)
{"name":"zhangsan","age":"字符串 1","anotherAge":1}
Person(name=zhangsan, age=1, anotherAge=1)

@JacksonAnnotationsInside 的简单使用

@JacksonAnnotationsInside 注解的作用是将多个注解组合到一起。

1)定义新的序列化注解

@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonSerialize(using = ObfuscatedIdSerializer.class)
public @interface NeedObfuscatedId {
}

2)定义新的反序列化注解

@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonDeserialize(using = ObfuscatedIdDeserializer.class)
public @interface NeedUnobfuscatedId {
}

3)在需要序列化的类上使用新的特定注解 @NeedObfuscatedId@NeedUnobfuscatedId,替换之前的 @JsonSerialize@JsonDeserialize 通用注解

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
    private String name;

    @NeedObfuscatedId
    @NeedUnobfuscatedId
    private int age;

    private int anotherAge;

    public static Person from(String name, int age) {
        return new Person(name, age, age);
    }
}

4)运行上面的 JacksonDemo2,控制台输出和之前一样。

5)把序列化和反序列化注解合并为同一个

@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonSerialize(using = ObfuscatedIdSerializer.class)
@JsonDeserialize(using = ObfuscatedIdDeserializer.class)
public @interface ObfuscatedIdSerde {
}

或者

@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@NeedObfuscatedId
@NeedUnobfuscatedId
public @interface ObfuscatedIdSerde {
}

6)在需要序列化的类上使用新的注解 ObfuscatedIdSerde 替换上面的 @NeedObfuscatedId@NeedUnobfuscatedId 注解。

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
    private String name;

    @ObfuscatedIdSerde
    private int age;

    private int anotherAge;

    public static Person from(String name, int age) {
        return new Person(name, age, age);
    }
}

7)运行上面的 JacksonDemo2,控制台输出和之前一样。

参考

  • Jackson 自定义序列化器
  • 改造了以前写的数据脱敏插件,更好用了

你可能感兴趣的:(Jackson 进阶之自定义序列化器)