Expected BEGIN_OBJECT but was BEGIN_ARRAY - Gson转对象过程报错

使用Gson由json转对象时报错:Expected BEGIN_OBJECT but was BEGIN_ARRAY,问题来源于转换的类型不明确导致。

Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

 报错代码:

public static void main(String[] args) throws Exception {
  FileInputStream in = new FileInputStream("d:\\c.txt");
   List json = new Gson().fromJson(new BufferedReader(new InputStreamReader(in)), List.class);
  in.close();
 }

解决方案:

使用TypeToken在创建对象时(编译)指明类型:

Type type = new TypeToken<List<Demo>>() {}.getType();
List json = new Gson().fromJson(new BufferedReader(new InputStreamReader(in)), type);