google gson fromjson() TypeToken

二次信任 提交于 2020-01-04 04:17:07

问题


I am not able to understand TypeToken of Google's GSON api's fromJson method. Below code is very complex to understand for me...

        Gson gson = new Gson();
        ArrayList<ID_Name_Address> al = new ArrayList<ID_Name_Address>();
        al = gson.fromJson(json, new TypeToken<List<ID_Name_Address>>(){}.getType());

What exactly is happening here : new TypeToken<List<ID_Name_Address>>(){}.getType()

is this a anonymous class? Throw some light on this code.


回答1:


TypeToken is a trick to obtain information about generics at runtime thanks to the fact that classes with fully specified generic superclasses make that data available through reflection.

The GSON user guide has a section on serializing/deserializing generics here: https://github.com/google/gson/blob/master/UserGuide.md#TOC-Serializing-and-Deserializing-Generic-Types

To specifically answer your question, it creates an anonymous object that captures the generics of TypeToken in its superclass data. That data is then extracted through reflection and packaged as a Type instance with getType() to avoid memory leaks due to the aforementioned anonymous class.



来源:https://stackoverflow.com/questions/41184226/google-gson-fromjson-typetoken

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