How do I globally register type adapters on gson?

I use gson in several places in my code. It seems that I need to register the type adapter I use every time, as shown below:

GsonBuilder gsonBuilder = new GsonBuilder();
 gsonBuilder.registerTypeAdapter(TypeA.class,new TypeAAdapter());
 gsonBuilder.registerTypeAdapter(TypeB.class,new TypeBAdapter());
 Gson gson = gsonBuilder.create();

Now, I can wrap this code in a utility function, or I can create a gsonbuilder singleton (is it thread safe?), But I don't think this common usage pattern is mentioned in the document

Are there some preferred ways to set up and maintain type adapters on gson, so I just need to worry about them in one place in my code?

Solution

Gson seems to be a thread - safe class You can find the function test to ensure thread safety in source code

Therefore, if the dependency injection framework is used, the gson instance can be injected into the class as a dependency

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>