Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gson gives "unchecked conversion" warning

Tags:

java

json

gson

I was trying to convert json strings to objects like this:

String jsonString = "[\"string1\", \"string2\"]";
Gson gson = new Gson();
List<String> list = gson.fromJson(jsonString, List.class);

There was this warning:

warning: [unchecked] unchecked conversion
            list = gson.fromJson(jsonString, List.class);
                                       ^
  required: List<String>
  found:    List

I tried to use List<String>.class

instead of List.class but I get a compile time error saying that I can't do that...

How can I get rid of this warning?

like image 670
Evan_HZY Avatar asked Feb 05 '14 23:02

Evan_HZY


People also ask

Which method gives warning from the compiler resulting from List to List unchecked conversion?

When we're using the Oracle or OpenJDK javac compiler, we can enable this warning by adding the compiler option -Xlint:unchecked.

What is unchecked warning in java?

An unchecked warning tells a programmer that a cast may cause a program to throw an exception somewhere else. Suppressing the warning with @SuppressWarnings("unchecked") tells the compiler that the programmer believes the code to be safe and won't cause unexpected exceptions.


1 Answers

You can use an array

String[] array = gson.fromJson(jsonString, String[].class);

or using TypeToken

Type listType = new TypeToken<ArrayList<String>>() {}.getType();
List<String> list  = gson.fromJson(jsonString, listType);
like image 194
Reimeus Avatar answered Oct 18 '22 08:10

Reimeus