我是Gson的新手,我正在尝试解析a中的对象数组Hashmap,但我得到了com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 3.
我的代码是
Map<String, String> listOfCountry = new HashMap<String, String>();
Gson gson = new Gson();
Type listType = new TypeToken<HashMap<String, String>>() {}.getType();
listOfCountry = gson.fromJson(sb.toString(), listType);
Run Code Online (Sandbox Code Playgroud)
和JSON是
[
{"countryId":"1","countryName":"India"},
{"countryId":"2","countryName":"United State"}
]
Run Code Online (Sandbox Code Playgroud)
你的JSON是一个对象数组,而不是类似的东西HashMap.
如果你的意思是你试图将其转换成一个List的HashMap小号......那么这就是你需要做的:
Gson gson = new Gson();
Type listType = new TypeToken<List<HashMap<String, String>>>(){}.getType();
List<HashMap<String, String>> listOfCountry =
gson.fromJson(sb.toString(), listType);
Run Code Online (Sandbox Code Playgroud)
编辑以添加以下评论:
如果你想反序列化到一个CountryPOJO 数组(这是更好的方法),它就像这样简单:
class Country {
public String countryId;
public String countryName;
}
...
Country[] countryArray = gson.fromJson(myJsonString, Country[].class);
Run Code Online (Sandbox Code Playgroud)
也就是说,使用以下内容真的更好Collection:
Type listType = new TypeToken<List<Country>>(){}.getType();
List<Country> countryList = gson.fromJson(myJsonString, listType);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11076 次 |
| 最近记录: |