java - 如何使用 Gson 将 JSON 对象字符串转换为 ArrayList?
问题描述
所以我有一个这样的国家的 JSON 字符串:
{
"details": [
{
"country_id": "1",
"name": "Afghanistan",
"regions": null
},
{
"country_id": "2",
"name": "Albania",
"regions": null
},
{
"country_id": "3",
"name": "Algeria",
"regions": null
},
... and so on
}
现在我想要一种方法来尝试将其转换为一个ArrayList
国家/地区。
public static ArrayList<GFSCountry> get() {
return new Gson().fromJson(countriesJson, new TypeToken<ArrayList<GFSCountry>>(){}.getType());
}
但我得到一个
Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path
根据要求,这是我的GFSCountry
课程:
@SerializedName("country_id")
@Expose
private String countryId;
@SerializedName("name")
@Expose
private String name;
@SerializedName("regions")
@Expose
private Object regions;
public String getCountryId() {
return countryId;
}
public void setCountryId(String countryId) {
this.countryId = countryId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Object getRegions() {
return regions;
}
public void setRegions(Object regions) {
this.regions = regions;
}
我知道我应该从 JSON 字符串或方法中调整一些东西。有什么帮助吗?
解决方案
由于该列表嵌套在您的 JSON 中,您将需要一个包含该列表的小型映射类。
尝试
static class GFSCountryList {
public List<GFSCountry> details;
}
public static List<GFSCountry> get() {
return new Gson().fromJson(countriesJson, GFSCountryList.class).details;
}
推荐阅读
- python - 在数据框中搜索值:为列设置值,如比较数据框的值(如果存在)
- unit-testing - 在单元测试期间设置 Kubernetes 资源的 metadata.DeletionTimestamp 字段的最佳方法是什么?
- vue.js - 如何使用事件总线在微服务之间进行通信?
- bootstrap-4 - 在 Bootstrap Datetimepicker 上每周日禁用特定时间
- python - 遍历中序如何打印值?
- windows - 如何在 Unidrv 框架上开发自己的打印机迷你驱动程序?
- javascript - 无法从 Debounce 中获取自定义挂钩数据
- reactjs - react-refresh-webpack-plugin 中的“SocketClient 不是构造函数”
- ios - Xcode 未使用正确的 ios SDK 版本编译
- visual-studio-code - 新的python交互式窗口单元格不指示它是否仍在运行