package com.imdroid.beidou.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import java.lang.reflect.Type;

/**
 * @author Layton
 * @date 2022/3/28 15:35
 */
public class GsonUtils {

    private static final Gson gson = new Gson();

    private static final Gson serializeNullGson = new GsonBuilder().serializeNulls().disableHtmlEscaping().create();

    private static final Gson serializeExposeGson = new GsonBuilder().serializeNulls().excludeFieldsWithoutExposeAnnotation().create();

    public static String toJsonSerializeNull(Object c) {
        return serializeNullGson.toJson(c);
    }

    public static String toJson(Object c) {
        return gson.toJson(c);
    }

    public static String toJsonExpose(Object c) {
        return serializeExposeGson.toJson(c);
    }

    public static <T> T fromJson(String json, Class<T> clz) {
        return gson.fromJson(json, clz);
    }

    public static <T> T fromJson(String json, Type typeOfT) {
        return gson.fromJson(json, typeOfT);
    }

    public static String getValue(JsonObject jsonObject, String key) {
        JsonElement element = jsonObject.has(key) ? jsonObject.get(key) : null;
        if (element == null) {
            return "";
        }
        if (element.isJsonObject()) {
            return element.getAsJsonObject().toString();
        } else if (element.isJsonNull()) {
            return "";
        } else if (element.isJsonArray()) {
            return element.getAsJsonArray().toString();
        } else  {
            if (element.getAsJsonPrimitive().isBoolean()) {
                return element.getAsBoolean() ? "true" : "false";
            } else {
                return element.getAsString();
            }
        }
    }

    public static Number getNumber(JsonElement element) { ;
        if (element == null) {
            return null;
        }
        if (element.isJsonNull()) {
            return null;
        } else {
            try {
                return element.getAsNumber();
            } catch (Exception e) {
                return null;
            }
        }
    }
}
