但是我无法从中得到答案。上面链接的答案:
public static List<MapData> getData(){ Gson gson = new Gson(); String jsonString = "[{\"id\":18,\"city\":\"test\",\"street\":\"test 1\",\"zipcode\":121209,\"state\":\"IL\",\"lat\":32.158138,\"lng\":34.807838},{\"id\":19,\"city\":\"test\",\"street\":\"1\",\"zipcode\":76812,\"state\":\"IL\",\"lat\":32.161041,\"lng\":34.810410}]"; Type type = new TypeToken<List<MapData>>(){}.getType(); return gson.fromJson(jsonString, type); }
它运作良好,但我想对泛型使用隐式运算符。见下文:
public static <T> List<T> getData(Class<T> classT){ Gson gson = new Gson(); String jsonString = "[{\"id\":18,\"city\":\"test\",\"street\":\"test 1\",\"zipcode\":121209,\"state\":\"IL\",\"lat\":32.158138,\"lng\":34.807838},{\"id\":19,\"city\":\"test\",\"street\":\"1\",\"zipcode\":76812,\"state\":\"IL\",\"lat\":32.161041,\"lng\":34.810410}]"; Type type = new TypeToken<List<T>>(){}.getType(); return gson.fromJson(jsonString, type); }
然后,我尝试将Class参数传递给方法:
List<MapData> data = getData(MapData.class); System.out.println(data.get(0).city);
然后出现一个错误:
java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to com.ssc.ctq.nav.util.MapData
谁能告诉我为什么会出现此错误?TypeToken类不支持隐式运算符吗?
您可以这样:
Gson gson = new Gson(); String jsonString = "[{\"id\":18,\"city\":\"test\",\"street\":\"test 1\",\"zipcode\":121209,\"state\":\"IL\",\"lat\":32.158138,\"lng\":34.807838},{\"id\":19,\"city\":\"test\",\"street\":\"1\",\"zipcode\":76812,\"state\":\"IL\",\"lat\":32.161041,\"lng\":34.810410}]"; List<Map> tmpList = gson.fromJson(jsonString); List<T> resultList = new Arraylist<T>(tmplist.size()); for(Map map:tmpList){ String tmpJson = gson.toJson(map); resultList.add(gson.fromJson(tmpJson, classT)); } return resultList;