package com.gh.gamecenter.core.utils

import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import org.json.JSONArray
import org.json.JSONObject


/**
 * Created by khy on 11/10/17.
 */
object GsonUtils {

    @JvmStatic
    val gson by lazy { Gson() }
    val gsonThatIgnoreNull by lazy {
        GsonBuilder()
            .serializeNulls()
            .create()
    }

    @JvmStatic
    fun <T> fromJson(json: String, t: Class<T>): T {
        return gson.fromJson(json, t)
    }

    @JvmStatic
    @Deprecated("部分 7.1.1 设备会出现 AssertionError，尽量不要在关键功能上使用此方法")
    fun <T> fromJsonList(json: JSONArray): List<T> {
        return try {
            val type = object : TypeToken<List<T>>() {}.type
            return gson.fromJson(json.toString(), type)
        } catch (e: Throwable) {
            listOf()
        }
    }

    @JvmStatic
    @Deprecated("部分 7.1.1 设备会出现 AssertionError，尽量不要在关键功能上使用此方法")
    fun <T> fromJsonList(json: String): List<T> {
        return try {
            val type = object : TypeToken<List<T>>() {}.type
            gson.fromJson(json, type)
        } catch (e: Throwable) {
            listOf()
        }
    }

    @JvmStatic
    fun toJson(any: Any?): String {
        return gson.toJson(any)
    }

    @JvmStatic
    fun toJsonIgnoreNull(any: Any?): String {
        return gsonThatIgnoreNull.toJson(any)
    }

    @JvmStatic
    fun isJSONValid(json: String): Boolean {
        try {
            JSONObject(json)
        } catch (e: Exception) {
            try {
                JSONArray(json)
            } catch (e: Exception) {
                return false
            }
        }
        return true
    }
}