我是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);
JSON是
[
{"countryId":"1","countryName":"India"},
{"countryId":"2","countryName":"United State"}
]
您的JSON是一个对象数组,没有类似的对象HashMap
。
如果您是想将其转换List
为HashMap
s的...,那么这就是您需要做的:
Gson gson = new Gson();
Type listType = new TypeToken<List<HashMap<String, String>>>(){}.getType();
List<HashMap<String, String>> listOfCountry =
gson.fromJson(sb.toString(), listType);
编辑以从以下注释中添加:
如果您想反序列化为一个Country
POJO数组(这确实是更好的方法),它很简单:
class Country {
public String countryId;
public String countryName;
}
...
Country[] countryArray = gson.fromJson(myJsonString, Country[].class);
就是说,最好使用Collection
:
Type listType = new TypeToken<List<Country>>(){}.getType();
List<Country> countryList = gson.fromJson(myJsonString, listType);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句