Gson解析list

方法原理:

String result = "[{\"id\":1,\"departmentId\":null,\"name\":\"威震天\",\"mobile\":\"13011111111\",\"telephone\":\"80000000\",\"gender\":1,\"email\":\"[email protected]\",\"position\":\"产品\",\"enable\":1},{\"id\":2,\"departmentId\":null,\"name\":\"测试\",\"mobile\":\"13000000000\",\"telephone\":\"811111111\",\"gender\":2,\"email\":\"[email protected]\",\"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());
}

输出:

威震天
测试

封装一:

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);

 

你可能感兴趣的:(Android开发)