import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.ToNumberStrategy
import com.google.gson.reflect.TypeToken
import com.google.gson.stream.JsonReader
import java.io.IOException
import java.lang.reflect.Type
import java.math.BigDecimal;
val gson: Gson = GsonBuilder()
.setObjectToNumberStrategy(AutoToNumberStrategy())
.create()
fun Gson.safetyToJson(any: Any) = try {
gson.toJson(any)
} catch (e: Exception) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
null
}
fun Any?.safetyToJson() = try {
gson.toJson(this)
} catch (e: Exception) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
null
}
inline fun
gson.fromJson(this, cls)
} catch (e: Exception) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
null
}
inline fun
try {
gson.fromJson(this, typeOf) as? T
} catch (e: Exception) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
null
}
/**
- author : Android 輪子哥
- github : https://github.com/getActivity/GsonFactory
- time : 2024/03/11
- desc : 自動轉換數值型別的策略
*/
class AutoToNumberStrategy : ToNumberStrategy {
@Throws(IOException::class)
override fun readNumber(in
: JsonReader): Number {
// Github issue 地址:https://github.com/getActivity/GsonFactory/issues/40
val numberString =in
.nextString()
val bigDecimal = BigDecimal(numberString)
// 判斷這個數值是浮點數還是整數
if (bigDecimal.scale() > 0) {
// 如果是浮點數,則用 double 型別裝載
return bigDecimal.toDouble()
}
// 如果是整數,則用 int 型別或者 long 型別裝載
return if (bigDecimal > BigDecimal.valueOf(Int.MAX_VALUE.toLong())) {
bigDecimal.toLong()
} else {
bigDecimal.toInt()
}
}
}