问题
Currently, I have a lot of occurences in my code that read as follows: result = new Gson().fromJson(someString, ResultContainer.class); Should I share the GSON object over all those places? If so, per object or static per class (potentially even superclass?)
I am asking mainly because if sharing the reference statically is fine, then why isn't the Gson object static in the first place? Unless one uses fancy custom serialization rules, the method above pretty much covers what one would want Gson to do.
回答1:
According to the GSON user guide:
The Gson instance does not maintain any state while invoking Json operations. So, you are free to reuse the same object for multiple Json serialization and deserialization operations.
It's not singleton because you can configure it differently via GsonBuilder.
回答2:
Sharing the Gson is fine.
You can configure a Gson using GsonBuilder therefore Gsonis not a singleton.
来源:https://stackoverflow.com/questions/32968565/instantiate-a-new-instance-of-gson-for-every-serialization