欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Gson解析工具类

程序员文章站 2022-03-13 12:50:12
...

  Gson解析工具类

包含对null  ,空字符串的处理

public class GsonUtils implements JsonSerializer<String>, JsonDeserializer<String> {

    private GsonUtils() {
    }

    public static <T> T parseJSON(String json, Class<T> clazz) {
        GsonBuilder gb = new GsonBuilder();
        gb.registerTypeAdapter(String.class, new GsonUtils());
        Gson gson = gb.create();
        T info = gson.fromJson(json, clazz);
        return info;
    }

    public static <T> T parseJSON(String json, Type type) {
        GsonBuilder gb = new GsonBuilder();
        gb.registerTypeAdapter(String.class, new GsonUtils());
        Gson gson = gb.create();
        T info = gson.fromJson(json, type);
        return info;
    }

    public static <T> List<T> jsonToList(String json, Class<? extends T[]> clazz) {
        Gson gson = new Gson();
        T[] array = gson.fromJson(json, clazz);
        return Arrays.asList(array);
    }

    /**
     * @param json
     * @param clazz
     * @return
     */
    public static <T> ArrayList<T> jsonToArrayList(String json, Class<T> clazz) {
        GsonBuilder gb = new GsonBuilder();
        gb.registerTypeAdapter(String.class, new GsonUtils());
        Type type = new TypeToken<ArrayList<JsonObject>>() {
        }.getType();
        ArrayList<JsonObject> jsonObjects = gb.create().fromJson(json, type);
        ArrayList<T> arrayList = new ArrayList<>();
        for (JsonObject jsonObject : jsonObjects) {
            arrayList.add(new Gson().fromJson(jsonObject, clazz));
        }
        return arrayList;
    }

    @Override
    public String deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        return json.getAsJsonPrimitive().getAsString();
    }

    @Override
    public JsonElement serialize(String src, Type typeOfSrc, JsonSerializationContext context) {
        if (src == null) {
            return new JsonPrimitive("");
        } else {
            return new JsonPrimitive(src.toString());
        }
    }
}

 

相关标签: gson