GSON解析泛型Json数组 [英] GSON parse generic Json Array

查看:180
本文介绍了GSON解析泛型Json数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题与此非常相似:
无法解析使用Gson的Json数组

My question is very similiar to this: Unable to parse Json array using Gson

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

But I cann't get the answer from it. The answer from above link:

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);     
}

效果很好,但我想在泛型上使用隐式运算符。见下:

It works well, but I want to use implicit operator on generic type. See below:

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参数传递给方法:

And then I try to pass the Class argument to the method:

List<MapData> data = getData(MapData.class);
System.out.println(data.get(0).city);

然后出现错误:

Then an error was arised:

java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to com.ssc.ctq.nav.util.MapData 

任何人都可以告诉我为什么会出现此错误吗? TypeToken类中不支持隐式运算​​符吗?

Can anyone tell me why I get this error? Is implicit operator is not supported in TypeToken class?

推荐答案

您可以这样做:

you can do like this:

     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;

这篇关于GSON解析泛型Json数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆