1

我的问题与此非常相似: Unable to parse Json array using Gson

但我无法从中得到答案。上面链接的答案:

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 类不支持隐式运算​​符吗?

4

3 回答 3

4

你可以这样做:

     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;
于 2013-09-10T08:11:18.830 回答
2

我遇到了同样的问题。来自TypeToken 的Javadoc

此语法不能用于创建具有通配符参数的类型文字,例如Class<?>or List<? extends CharSequence>

您必须明确指出Tin的类型TypeToken<T>,而不是泛型。

于 2013-09-10T07:42:37.587 回答
0

您可以使用此方法来解析通用json 字符串以进行映射

    public Map<String, String> getMapFromJson(String jsonString) {
    Map<String, String> map = new HashMap<>();
    try {
        JSONObject object = new JSONObject(jsonString);
        Iterator<?> iterator = object.keys();
        while (iterator.hasNext()) {
            String key = (String) iterator.next();
            if(!key.isEmpty() && !object.getString(key).isEmpty()){
                map.put(key, object.getString(key));
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return map;
}
于 2015-04-14T10:20:46.083 回答