Derrick
Derrick

Reputation: 4445

TypeToken usage mandatory?

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.

Upvotes: 5

Views: 1897

Answers (1)

Developerick
Developerick

Reputation: 46

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

Upvotes: 3

Related Questions