背景:本地放置了一個json文件,讀取改文件爲json字符串數據,然後將字符串轉爲List集合。
轉爲List集合時報錯:
source[0] of type com.google.gson.internal.LinkedTreeMap cannot be stored in destination array of type
代碼如下:
//從本地json讀取城市數據到數據庫
String cityJsonString = AppUtils.getStringFromRawFile(getApplicationContext(), R.raw.city);
if (TextUtils.isEmpty(cityJsonString)) {
return;
}
List<WeatherCity> cityList = GsonUtil.fromJsonToList(cityJsonString);
public static <T> List<T> fromJsonToList(String json) {
try {
Type type = new TypeToken<List<T>>(){}.getType();
if (TextUtils.isEmpty(json) || type == null) return null;
return sGson.fromJson(json, type);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
而如果直接把泛型T指定爲具體的類,就可以正常轉化爲List。
解決辦法就是:在使用泛型過程中,必須要具體到某一個類,不用使用泛型代替。
public static <T> List<T> fromJsonToList(String json, Type type) {
if (TextUtils.isEmpty(json) || type == null) return null;
return sGson.fromJson(json, type);
}
調用:
List<WeatherCity> cityList = GsonUtil.fromJsonToList(cityJsonString,new TypeToken<List<WeatherCity>>(){}.getType());