In the Gson docs, I ran across this construct to use for converting a list of JSONified Spotify Artist objects back into the ArrayList of objects. I use this in the onRestoreInstanceState().
However, I have never seen the {} after a declaration. Can someone explain to me what it means? I know that getType() is a member class but why the {}?
Type type = new TypeToken<List<Artist>>() {}.getType();
mArtistsList = new Gson().fromJson(jsonSearchResults, type);
{}
means an anonymous class that doesn't override any methods. Here's another anonymous class you've seen before:
Runnable r = new Runnable() {
@Override
public void run() {
}
};
.getType()
returns a java.lang.reflect.Type
which Gson uses to identify which TypeAdapter
it's going to use to serialize and deserialize your Object
/ JSON String
.
See my answer here for more information on how Gson uses this to infer the generic type parameter; the short version is that it needs to use an anonymous class or it wouldn't work.
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