GithubHelp home page GithubHelp logo

boboopensource / gson Goto Github PK

View Code? Open in Web Editor NEW
0.0 1.0 1.0 73 KB

Serialization and deserialization of custom enum types ,based on gson(基于gson,自定义枚举类型的序列化反序列化)

Java 100.00%

gson's Introduction

Serialization and deserialization of custom enum types ,based on gson

基于gson,自定义枚举类型序列化反序列化,实际效果如下:

实体类:OrderDO:{orderNo="202109050001", status=StatusEnum.PENDING} <--> json串:{"orderNo":"202109050001","status":{"value":2,"desc":"处理中"}}

需求背景:将枚举元素序列化为带有值和说明(value/desc)的json串,反序列化则基于值(value)进行匹配

问题:由于gson的JsonSerializer、JsonDeserializer只支持单个具体类型,如果有多个enum类型,就得实现多个JsonSerializer、JsonDeserializer,并注册多次,只能寻找其他解决方式

解决方式:gson的TypeAdapterFactory支持根据对象类型动态返回一个TypeAdapter,执行序列化与反序列化,正好适用

1、自定义BasicEnumTypeAdapterFactory(实现TypeAdapterFactory#create方法)
逻辑:如果枚举类实现了BasicEnum,使用BasicEnumTypeAdapter执行序列化、反序列化
2、自定义BasicEnumTypeAdapter(实现TypeAdapter#write,TypeAdapter#read)
逻辑:将所有实现了BasicEnum的枚举类(如StatusEnum)序列化为类似于{"value":"1","desc":"初始化"}这种包含value、desc的json串)
3、使用GsonBuilder#registerTypeAdapterFactory注册BasicEnumTypeAdapterFactory

测试类:EnumSerializeDeserializeTest

gson's People

Contributors

boboopensource avatar

Watchers

 avatar

Forkers

333bkz

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.