Gson解析list

方法原理:

String result = "[{\"id\":1,\"departmentId\":null,\"name\":\"威震天\",\"mobile\":\"13011111111\",\"telephone\":\"80000000\",\"gender\":1,\"email\":\"578514363@qq.com\",\"position\":\"产品\",\"enable\":1},{\"id\":2,\"departmentId\":null,\"name\":\"测试\",\"mobile\":\"13000000000\",\"telephone\":\"811111111\",\"gender\":2,\"email\":\"555555555@qq.com\",\"position\":\"前端工程师\",\"enable\":1}]"; Gson gson=new Gson(); Type type = new TypeToken>(){}.getType(); List list = gson.fromJson(result, type); //打印测试 for(User i:list){ System.out.println(i.getName()); }

【Gson解析list】输出:
威震天 测试

封装一:
public static List jsonToList(String s, Class cls) { T[] arr = new Gson().fromJson(s, cls); return Arrays.asList(arr); }

调用:
List list = jsonToList(result,User[].class);

封装二:
public static List jsonToList(String json, Class cls) { List list = new ArrayList(); JsonArray array = new JsonParser().parse(json).getAsJsonArray(); for(final JsonElement elem : array){ list.add(new Gson().fromJson(elem, cls)); } return list; }

调用:
List list = jsonToList(result,User.class);


    推荐阅读