Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

google gson fromjson() TypeToken

Tags:

java

json

gson

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.

like image 216
JPG Avatar asked Dec 16 '16 12:12

JPG


People also ask

What is TypeToken in Gson?

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.

What does Gson fromJson do?

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.

Is Gson better than JSON?

GSON can use the Object definition to directly create an object of the desired type. While JSONObject needs to be parsed manually.


1 Answers

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.

like image 131
Kiskae Avatar answered Oct 13 '22 00:10

Kiskae