【问题标题】:How to make fromJson of Gson create arraylilst of object如何让 Gson 的 fromJson 创建对象的arraylilst
【发布时间】:2018-03-24 01:34:12
【问题描述】:

我有一个包含JSONObject 数组的json 文件,在读取并将其转换为字符串后,我想创建一个Java 对象的ArrayList,这是我目前的代码:

ArrayList<CountryCode> arrayList;
arrayList = new ArrayList<CountryCode>();
try {
        InputStream ims = context.getResources().getAssets().open("json/" + "countryCodes.json");
        reader = new InputStreamReader(ims);
        int size = ims.available();
        byte[] buffer = new byte[size];
        ims.read(buffer);
        ims.close();
        json = new String(buffer, "UTF-8");
        arrayList = gson.fromJson(json , ArrayList.class);
        Log.i("countrycode", String.valueOf(arrayList.get(0).getCode()));
    } catch (IOException e) {
        e.printStackTrace();
    }

其中 CountryCode 是模型类,有 name 字段,countrycode 是 JSONObjects 的映射(每个 json 对象都有 name 和 countrycode)

出现错误:

ClassCastException: com.google.gson.internal.LinkedTreeMap 不能 转换为 com.myhealthahand.hah.objects.CountryCode

【问题讨论】:

  • 提供更多细节,如 json 字符串和 CountryCode 类。

标签: java android json oop gson


【解决方案1】:

参考以下代码

 **List<CountryCode> arrayList;
        
    Type collectionType = new TypeToken<List<CountryCode>>() {}.getType();**

try {
    InputStream ims = context.getResources().getAssets().open("json/" + "countryCodes.json");
    reader = new InputStreamReader(ims);
    int size = ims.available();
    byte[] buffer = new byte[size];
    ims.read(buffer);
    ims.close();
    json = new String(buffer, "UTF-8");
     
    **arrayList = new Gson().fromJson(json, collectionType);**

    Log.i("countrycode", String.valueOf(arrayList.get(0).getCode()));
} catch (IOException e) {
    e.printStackTrace();
}

【讨论】:

    【解决方案2】:

    使用TypeToken 而不是ArrayList.class

    Gson gson = new Gson();
    Type type = TypeToken.getParameterized(ArrayList.class, CountryCode).getType();   
    ArrayList<ArrayObject> arrayList = gson.fromJson(json, type);
    

    如果 gson 高于 2.8.0,这也有效

    【讨论】:

      【解决方案3】:

      你需要像这样定义类型列表:

      Type listType = new TypeToken<ArrayList<CountryCode>>(){}.getType();
      
      arrayList = new Gson().fromJson(json, listType);
      

      【讨论】:

      • listType 有什么作用?
      • 它定义了要转换的 ArrayList 的类型,在你的情况下是 ArrayList
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多