google gson fromjson() TypeToken Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of google gson fromjson() TypeToken without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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.


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:

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.

We are here to answer your question about google gson fromjson() TypeToken - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji