How to globally register adapter types on Gson?

I use gson in several places in my code, and it seems that every time I need to register the types of adapters that I use, for example:

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 singleton gsonBuilder (is it thread safe?), But it seems strange to me that this common usage pattern is not mentioned in the documentation.

Is there any preferred method for setting type-and-forget adapter types on gson, so that I only need to worry about them in one place in my code?

+4
source share
2 answers

Gson seems to be a thread safe class. A functional test that ensures thread safety can be found in the source code .

That way, you can inject a Gson instance into your classes as dependencies if you use the dependency injection infrastructure.

+1
source

register TypeAdapterFactory in grails-app/conf/spring/resources.groovy :

 beans { localDateAdapterFactory(LocalDateAdapterFactory) } 
0
source

Source: https://habr.com/ru/post/1386164/


All Articles