使用google gson在hashmap中的json数组

Jit*_*ati 7 java json gson

我是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)

Bri*_*ach 8

你的JSON是一个对象数组,而不是类似的东西HashMap.

如果你的意思是你试图将其转换成一个ListHashMap小号......那么这就是你需要做的:

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)

  • 不,我只需要将所有数据放入哈希映射中。不是单个 hashmap 中的 hashmap 列表 (2认同)
  • “绝对没有意义”有点苛刻,您可以简单地将键和值放在哈希图中。键countryId和countryName,值是json字符串或对象。是的,创建一个pojo很不错,但是可以用作中介。http://stackoverflow.com/a/14944513/106261 (2认同)