Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Gson源码总结 #94

Open
zgq105 opened this issue May 3, 2022 · 0 comments
Open

Gson源码总结 #94

zgq105 opened this issue May 3, 2022 · 0 comments

Comments

@zgq105
Copy link
Owner

zgq105 commented May 3, 2022

1.gson的主要解决什么问题?如何实现的?主要的原理?

gson的主要解决什么问题?
gson是谷歌出品的java库,主要是解决java对象和json字符串之间序列化和反序列化的问题。当将java对象转成json字符串的过程就是序列化的操作,提供的API是toJson(...);反之,将json字符串转成java对象的过程就是反序列化,提供的API是fromJson(...)。序列化的目的是为了方便数据的传输,反序列过程同时将数据还原回java对象。

如何实现的?主要的原理?
实现的过程主要分为序列化和反序列化的过程。序列化的过程主要是通过反射的原理将字段解析出来拼接成json(主要类:JsonWriter、TypeAdapter)。而反序列化的过程正好相反,将json解析出来,然后通过反射创建创建出对象,并且给对象的属性赋值。(主要类:JsonReader、TypeAdapter、TypeToken)

2.在实现中使用到了哪些设计模式?

1.抽象工厂模式
抽象工厂类TypeAdapterFactory,抽象产品类TypeAdapter,TypeAdapterFactory的实现类有CollectionTypeAdapterFactory、Excluder、ReflectiveTypeAdapterFactory、SingleTypeFactory等等。

2.策略模式
接口ToNumberStrategy、实现类ToNumberPolicy;接口FieldNamingStrategy、实现类FieldNamingPolicy,这里通过枚举类的方式来实现策略模式,代码可读性高。

3.建造者模式
GsonBuilder类主要用来构建Gson类的对象,建造者的模式就是为了通过链式编程的方式构建类的对象,每个方法给类中的属性赋值。
举例如下:
Gson gson2 = new GsonBuilder() .setPrettyPrinting() .serializeNulls() .disableJdkUnsafe() .create();

3.参考

gson

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant