android gson 扩展, 序列化int类型被转double 问题
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()
}
}
}