json解析-將json字符串轉爲List集合

背景:本地放置了一個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());

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章