版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/RekaDowney/article/details/52292567
JDK 版本 |
---|
Gson 版本 |
---|
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.7</version>
</dependency>
Gson
是实现对象序列化和反序列化的利器,但是Gson
在(反)序列化枚举时默认是根据枚举值的名称来实现的,如果你想要在(反)序列化枚举时输出自己定义的枚举属性,那么此时至少有两种选择:
- 继承
TypeAdapter
抽象类并实现其中的抽象方法 - 实现
JsonSerializer
和/或JsonDeserializer
接口
我通常是选择第二种方式,即实现接口的方式来自定义(反)序列化过程。比如下面这个实例:
针对JDK1.8
新的时间API
中的LocalDate
进行自定义(反)序列化过程:
import com.google.gson.*;
import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class LocalDateTypeAdapter implements JsonSerializer<LocalDate>, JsonDeserializer<LocalDate> {
private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
@Override
public JsonElement serialize(LocalDate src, Type typeOfSrc, JsonSerializationContext context) {
return null == src ? null : new JsonPrimitive(formatter.format(src));
}
@Override
public LocalDate deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return null == json ? null : LocalDate.parse(json.getAsString(), formatter);
}
}
当注册了该
TypeAdapter
的
Gson
在序列化
LocalDate
类型时,会调用其中的
serialize
方法,此时如果
LocalDate
实例非空的话,我们将调用
formatter.format(src)
方法将
LocalDate