天天看点

Gson的fromJson指定转换类型

String testStr = "{\"content\":[{\"state\":\"02\",\"billno\":\"161114002902010026\",\"note\":\"直投借款合同已放款,不允许重复放款\"}],\"result\":\"0000\"}";

Gson gson = new Gson();

Map map = gson.fromJson(testStr, HashMap.class);

System.out.println(map);

//这个写法有问题转换会有问题

List<Map> wrong = gson.fromJson(MapUtils.getString(map, "content"), ArrayList.class);

System.out.println(wrong);

//下面的写法OK

List<Map> right = gson.fromJson(MapUtils.getString(map, "content"), new TypeToken<List<Map<String, String>>>() { }.getType());

System.out.println(right);