I use gson in several places in my code, and it seems that every time, I need to register the type adapters I use, like so:
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 it seems strange to me that this common usage pattern doesn’t get any mention in the documentation.
Is there some preferred method to set-and-forget type adapters on gson, so that I would only have to worry about them in one place in my code?
Gson seems to be a thread safe class. The functional test that ensures thread-safety can be found in source code.
So you can inject Gson instance in your classes as a dependency if you are using dependency injection framework.