0

Can someone enlighten me what the following code does as described here https://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Generic-Types?

Type collectionType = new TypeToken<Collection<Integer>>(){}.getType();

I am using it to convert JSON to a Java Map which works perfectly fine, but I haven't seen such a syntax before. Here is my code

Map<String, Object> map = new Gson().fromJson(reader, new TypeToken<HashMap<String, Object>>() {}.getType());
Michael
  • 393
  • 2
  • 4
  • 20
  • That was not helpful and not my question. – Michael Jan 16 '17 at 21:37
  • the only `TypeToken` responsibility is holding the type parameter of any type (except `void` and all 8 primitive ones). Thus, `new TypeToken>(){}` may look unusual but it effectively means: 1) the type token defines `Collection` type information (because you can't do `Collection.class` in java); 2) anonymous type token subtype is created because the **actual** type information can be stored as a type parameter whilst `T` in the super `TypeToken` class is just a wildcard and can't hold any real type info. – Lyubomyr Shaydariv Jan 17 '17 at 11:38
  • Once the anonymous type is defined with a good type parameterization, you can get its "rendered" type with `.getType()` as `Type` which can be parameterized or whatever you might want it to be since `Class` cannot contain generic types information. Unfortunately, this is because of how generic types work in Java and why the work-around like `TypeToken` exists. If I'm not mistaken, in .NET/C# world you could simply write `typeof(Collection)` as a counter-part of `new TypeToken>(){}.getType()` in Java. – Lyubomyr Shaydariv Jan 17 '17 at 11:41
  • Thanks for your explanation, exactly what I asked for. Sadly other people thought the question was worthy of downvoting. – Michael Jan 20 '17 at 10:44
  • You're welcome. Yes, sometimes questions are closed with wrong reason, but you might be interested in reading further at https://stackoverflow.com/questions/30005110/how-does-gson-typetoken-work , http://stackoverflow.com/questions/20773850/gson-typetoken-with-dynamic-arraylist-item-type , http://stackoverflow.com/questions/14139437/java-type-generic-as-argument-for-gson (which your question might duplicate as the real reason) -- there are some better explanations. I don't think your question is worthy for downvoting because type tokens is really a more advanced topic. – Lyubomyr Shaydariv Jan 20 '17 at 10:59
  • If you're familiar with Spring, you also might see `ParameterizedTypeReference` that's used for the exactly same reasons (and probably `TypeReference` in Jackson if I'm not mistaken). Just because Java generics are erased, people found a more or less "magic" workaround. :) – Lyubomyr Shaydariv Jan 20 '17 at 11:03

0 Answers0