如何从Gson的Json创建对象的数组列表

uinbv5nw  于 2022-11-06  发布在  其他
关注(0)|答案(3)|浏览(211)

我有一个json文件,其中有JSONObject数组,阅读并转换为字符串后,我想创建一个ArrayList的Java对象,以下是我目前的代码:

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是模型类,具有名称、国家代码字段,这是来自JSONObjects的Map(每个json对象都具有名称和国家代码)
获取错误:
类转换异常错误:无法将链接树Map强制转换为对象

rmbxnbpk

rmbxnbpk1#

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

Type listType = new TypeToken<ArrayList<CountryCode>>(){}.getType();

arrayList = new Gson().fromJson(json, listType);
ajsxfq5m

ajsxfq5m2#

使用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,也可以使用此功能

dfty9e19

dfty9e193#

参考以下代码


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

相关问题