创新实训——使用Gson下发数据

1.Gson简介

GSON是Google开发的Java API,用于转换Java对象和Json对象。

Gson提供了fromJson() 和toJson() 两个直接用于解析和生成的方法,前者实现反序列化,后者实现了序列化。

2.json的生成

new Gson().toJson(list);

3.json的解析

将json转换成ArrayList

public static <T> ArrayList<T> jsonToArrayList(String json, Class<T> clazz) {
        Type type = new TypeToken<ArrayList<JsonObject>>() {
        }.getType();
        ArrayList<JsonObject> jsonObjects = new Gson().fromJson(json, type);
        ArrayList<T> arrayList = new ArrayList<>();
        for (JsonObject jsonObject : jsonObjects) {
            arrayList.add(new Gson().fromJson(jsonObject, clazz));
        }
        return arrayList;
    }

将json转换为List<String> 

public static List<String> jsonToStringList(String string) {
        Type listType = new TypeToken<List<String>>() {
        }.getType();
        return new Gson().fromJson(string, listType);
    }

猜你喜欢

转载自blog.csdn.net/UnLongChemin/article/details/82107835