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.
Class TypeToken<T> Represents a generic type T . Java doesn't yet provide a way to represent generic types, so this class does. Forces clients to create a subclass of this class which enables retrieval the type information even at runtime.
As many of you know already Gson is a great Java library that can be used to convert Java Objects into their JSON representation. It works also in reverse order deserializing the specified JSONObject or JSONArray into an object of the specified class.
GSON can use the Object definition to directly create an object of the desired type. While JSONObject needs to be parsed manually.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With