方法原理:
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<ArrayList<User>>(){}.getType();
List<User> list = gson.fromJson(result, type);
//打印测试
for(User i:list){
System.out.println(i.getName());
}
输出:
威震天
测试
封装一:
public static <T> List<T> jsonToList(String s, Class<T[]> cls) {
T[] arr = new Gson().fromJson(s, cls);
return Arrays.asList(arr);
}
调用:
List<User> list = jsonToList(result,User[].class);
封装二:
public static <T> List<T> jsonToList(String json, Class<T> cls) {
List<T> list = new ArrayList<T>();
JsonArray array = new JsonParser().parse(json).getAsJsonArray();
for(final JsonElement elem : array){
list.add(new Gson().fromJson(elem, cls));
}
return list;
}
调用:
List<User> list = jsonToList(result,User.class);