Android Gson 工具類

DevUtils Github

方法 註釋
toJson 將對象轉換爲 JSON String
fromJson 將 JSON String 映射爲指定類型對象
isJSON 判斷字符串是否 JSON 格式
toJsonIndent JSON String 縮進處理
createGson 創建 GsonBuilder
createGsonExcludeFields 創建過濾指定修飾符字段 GsonBuilder
getArrayType 獲取 Array Type
getListType 獲取 List Type
getSetType 獲取 Set Type
getMapType 獲取 Map Type
getType 獲取 Type
package dev.other;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;

import java.io.StringReader;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.Set;

import dev.utils.JCLogUtils;

/**
 * detail: Gson 工具類
 * @author Ttt
 * <pre>
 *     Gson 詳細使用
 *     @see <a href="https://www.jianshu.com/p/d62c2be60617"/>
 * </pre>
 */
public final class GsonUtils {

    private GsonUtils() {
    }

    // 日誌 TAG
    private static final String TAG = GsonUtils.class.getSimpleName();
    // Object 轉 JSON 字符串
    private static final Gson TO_GSON = createGson(true).create();
    // JSON 字符串轉 T Object
    private static final Gson FROM_GSON = createGson(true).create();
    // JSON 縮進
    private static final Gson INDENT_GSON = createGson(true).setPrettyPrinting().create();

    // ============
    // = 轉換方法 =
    // ============

    /**
     * 將對象轉換爲 JSON String
     * @param object {@link Object}
     * @return JSON String
     */
    public static String toJson(final Object object) {
        return toJson(object, TO_GSON);
    }

    /**
     * 將對象轉換爲 JSON String
     * @param object {@link Object}
     * @param gson   {@link Gson}
     * @return JSON String
     */
    public static String toJson(final Object object, final Gson gson) {
        if (gson != null) {
            try {
                return gson.toJson(object);
            } catch (Exception e) {
                JCLogUtils.eTag(TAG, e, "toJson");
            }
        }
        return null;
    }

    // =

    /**
     * 將 JSON String 映射爲指定類型對象
     * @param json     JSON String
     * @param classOfT {@link Class} T
     * @param <T>      泛型
     * @return instance of type
     */
    public static <T> T fromJson(final String json, final Class<T> classOfT) {
        return fromJson(json, classOfT, FROM_GSON);
    }

    /**
     * 將 JSON String 映射爲指定類型對象
     * @param json     JSON String
     * @param classOfT {@link Class} T
     * @param gson     {@link Gson}
     * @param <T>      泛型
     * @return instance of type
     */
    public static <T> T fromJson(final String json, final Class<T> classOfT, final Gson gson) {
        if (gson != null) {
            try {
                return gson.fromJson(json, classOfT);
            } catch (Exception e) {
                JCLogUtils.eTag(TAG, e, "fromJson");
            }
        }
        return null;
    }

    // =

    /**
     * 將 JSON String 映射爲指定類型對象
     * @param json    JSON String
     * @param typeOfT {@link Type} T
     * @param <T>     泛型
     * @return instance of type
     */
    public static <T> T fromJson(final String json, final Type typeOfT) {
        return fromJson(json, typeOfT, FROM_GSON);
    }

    /**
     * 將 JSON String 映射爲指定類型對象
     * @param json    JSON String
     * @param typeOfT {@link Type} T
     * @param gson    {@link Gson}
     * @param <T>     泛型
     * @return instance of type
     */
    public static <T> T fromJson(final String json, final Type typeOfT, final Gson gson) {
        if (gson != null) {
            try {
                return gson.fromJson(json, typeOfT);
            } catch (Exception e) {
                JCLogUtils.eTag(TAG, e, "fromJson");
            }
        }
        return null;
    }

    // ============
    // = 其他方法 =
    // ============

    /**
     * 判斷字符串是否 JSON 格式
     * @param json 待校驗 JSON String
     * @return {@code true} yes, {@code false} no
     */
    public static boolean isJSON(final String json) {
        JsonElement jsonElement;
        try {
            jsonElement = new JsonParser().parse(json);
        } catch (Exception e) {
            return false;
        }
        if (jsonElement == null) {
            return false;
        }
        if (!jsonElement.isJsonObject()) {
            return false;
        }
        return true;
    }

    /**
     * JSON String 縮進處理
     * @param json JSON String
     * @return JSON String
     */
    public static String toJsonIndent(final String json) {
        return toJsonIndent(json, INDENT_GSON);
    }

    /**
     * JSON String 縮進處理
     * @param json JSON String
     * @param gson {@link Gson}
     * @return JSON String
     */
    public static String toJsonIndent(final String json, final Gson gson) {
        if (gson != null) {
            try {
                JsonReader reader = new JsonReader(new StringReader(json));
                reader.setLenient(true);
                JsonParser jsonParser = new JsonParser();
                JsonElement jsonElement = jsonParser.parse(reader);
                return gson.toJson(jsonElement);
            } catch (Exception e) {
                JCLogUtils.eTag(TAG, e, "toJsonIndent");
            }
        }
        return null;
    }

    // =

    /**
     * Object 轉 JSON String 並進行縮進處理
     * @param object {@link Object}
     * @return JSON String
     */
    public static String toJsonIndent(final Object object) {
        return toJsonIndent(object, INDENT_GSON);
    }

    /**
     * Object 轉 JSON String 並進行縮進處理
     * @param object {@link Object}
     * @param gson   {@link Gson}
     * @return JSON String
     */
    public static String toJsonIndent(final Object object, final Gson gson) {
        if (gson != null) {
            try {
                return gson.toJson(object);
            } catch (Exception e) {
                JCLogUtils.eTag(TAG, e, "toJsonIndent");
            }
        }
        return null;
    }

    // ========
    // = Gson =
    // ========

    /**
     * 創建 GsonBuilder
     * @param serializeNulls 是否序列化 null 值
     * @return {@link GsonBuilder}
     */
    public static GsonBuilder createGson(final boolean serializeNulls) {
        GsonBuilder builder = new GsonBuilder();
        if (serializeNulls) builder.serializeNulls();
        return builder;
    }

    /**
     * 創建過濾指定修飾符字段 GsonBuilder
     * @param builder   {@link GsonBuilder}
     * @param modifiers 需過濾不處理的字段修飾符 {@link Modifier}
     * @return {@link GsonBuilder}
     */
    public static GsonBuilder createGsonExcludeFields(final GsonBuilder builder, final int... modifiers) {
        if (builder != null) {
            return builder.excludeFieldsWithModifiers(modifiers);
        }
        return null;
    }

    // ========
    // = Type =
    // ========

    /**
     * 獲取 Array Type
     * @param type Bean.class
     * @return Bean[] Type
     */
    public static Type getArrayType(final Type type) {
        return TypeToken.getArray(type).getType();
    }

    /**
     * 獲取 List Type
     * @param type Bean.class
     * @return List<Bean> Type
     */
    public static Type getListType(final Type type) {
        return TypeToken.getParameterized(List.class, type).getType();
    }

    /**
     * 獲取 Set Type
     * @param type Bean.class
     * @return Set<Bean> Type
     */
    public static Type getSetType(final Type type) {
        return TypeToken.getParameterized(Set.class, type).getType();
    }

    /**
     * 獲取 Map Type
     * @param keyType   Key.class
     * @param valueType Value.class
     * @return Map<Bean> Type
     */
    public static Type getMapType(final Type keyType, final Type valueType) {
        return TypeToken.getParameterized(Map.class, keyType, valueType).getType();
    }

    /**
     * 獲取 Type
     * @param rawType       raw type
     * @param typeArguments type arguments
     * @return Type
     */
    public static Type getType(final Type rawType, final Type... typeArguments) {
        return TypeToken.getParameterized(rawType, typeArguments).getType();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章