Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeToken usage mandatory?

Tags:

java

json

gson

Is is mandatory to use TypeToken (as recommended in the Gson doc) as type when converting a list into json like below -

new Gson().toJson(dateRange, new TypeToken<List<String>>() {}.getType()); 

For me below code is also working -

new Gson().toJson(dateRange, List.class);

Just want to make sure that code doesn't break.

like image 890
developerick Avatar asked Oct 16 '22 23:10

developerick


1 Answers

As per docs -

If the object that your are serializing/deserializing is a ParameterizedType (i.e. contains at least one type parameter and may be an array) then you must use the toJson(Object, Type) or fromJson(String, Type) method. Here is an example for serializing and deserializing a ParameterizedType:

 Type listType = new TypeToken<List<String>>() {}.getType();
 List<String> target = new LinkedList<String>();
 target.add("blah");

 Gson gson = new Gson();
 String json = gson.toJson(target, listType);
 List<String> target2 = gson.fromJson(json, listType);

This is the special case, in other cases you can use class type directly. For reference - http://google.github.io/gson/apidocs/com/google/gson/Gson.html

Hope this helps

like image 161
Developerick Avatar answered Nov 15 '22 07:11

Developerick