我的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是模型类,其中包含name,countrycode字段,这是JSONObjects的映射(每个json对象都有名称和国家代码)
获取错误:
ClassCastException:com.google.gson.internal.LinkedTreeMap不能 施放到com.myhealthathand.hah.objects.CountryCode
答案 0 :(得分:1)
您需要定义类型列表,如下所示:
Type listType = new TypeToken<ArrayList<CountryCode>>(){}.getType();
arrayList = new Gson().fromJson(json, listType);
答案 1 :(得分:0)
参考以下代码
**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 :(得分:0)
使用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
,这也有效