Gson字符串转List对象[泛型操作]

根据集合转换成JsonArray[Gson工具包]集合,然后通过Gson工具类直接遍历转化List实体对象的过程。
        //模拟服务端json数据
        String json = "[\n" +
                "        {\n" +
                "          \"name\": \"张三\",\n" +
                "          \"code\": \"zhangsan\"\n" +
                "        },\n" +
                "        {\n" +
                "          \"name\": \"李四\",\n" +
                "          \"code\": \"lisi\"\n" +
                "        },\n" +
                "        {\n" +
                "          \"name\": \"王五\",\n" +
                "          \"code\": \"wangwu\"\n" +
                "        }\n" +
                "      ]";
        List peopleInfoList = parseString2List(json,PeopleInfo.class);
/**
     * Gson字符串数组转成List对象[泛型操作]
     * author: JayGengi 60167
     * email:  [email protected]
     * time:  2018/04/13 10:01
     */
    public  List parseString2List(String json,Class clazz) {
        //泛型转换
        Type type = new ParameterizedTypeImpl(clazz);
        List list =  new Gson().fromJson(json, type);
        return list;
    }
/**
     * Gson解析不支持泛型,利用ParameterizedType获取泛型参数类型
     * author: JayGengi 60167
     * email:  [email protected]
     * time:  2018/04/13 10:01
     */
    private class ParameterizedTypeImpl implements ParameterizedType {
        Class clazz;

        public ParameterizedTypeImpl(Class clz) {
            clazz = clz;
        }
        @Override
        public Type[] getActualTypeArguments() {
            //返回实际类型组成的数据
            return new Type[]{clazz};
        }
        @Override
        public Type getRawType() {
            //返回原生类型,即HashMap
            return List.class;
        }
        @Override
        public Type getOwnerType() {
            //返回Type对象
            return null;
        }
    }

你可能感兴趣的:(Gson字符串转List对象[泛型操作])