5

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.

Gowthaman M
  • 8,057
  • 8
  • 35
  • 54
Derrick
  • 3,669
  • 5
  • 35
  • 50
  • Possible duplicate of [When to use google Gson's tojson method which accepts type as a parameter? public String toJson(Object src, Type typeOfSrc)](https://stackoverflow.com/questions/35601355/when-to-use-google-gsons-tojson-method-which-accepts-type-as-a-parameter-publi) – user158037 Feb 02 '18 at 12:42

1 Answers1

3

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