Gson 优雅实现多个枚举的自定义(反)序列化过程

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/RekaDowney/article/details/52292567
JDK版本

JDK版本.jpg

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);
    }

}
 
    
 
    
  当注册了该 TypeAdapterGson在序列化 LocalDate类型时,会调用其中的 serialize方法,此时如果 LocalDate实例非空的话,我们将调用 formatter.format(src)方法将 LocalDate
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值