Instantiate a new instance of GSON for every serialization?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 14:23:40

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!