使用 gson android 创建字符串到 json 的常用函数

common function for creating string to json with gson android

我想创建一个可以使用 Gson 将字符串转换为 JSON 的函数,就像我将响应 JSON 传递给该函数或者该函数将 return 我一个对象 例如。

fun convertJsonToModel(response:string,/*class that i want to convert*/){
  val gson = Gson()
  gson.fromJson(jsonString, /*class that i pass i args*/)
  return /* same class object that i pass in args*/
}

I want to use like this

var model1 = convertJsonToModel(response,Model1.class)
var model2 = convertJsonToModel(response,Model2.class)
var model3 = convertJsonToModel(response,Model3.class)

我不知道如何在函数 args 中传递 class,然后使用转换后的对象传递 return 请帮忙

你可以使用 Gson 的 fromJson():

val gson = Gson()
gson.fromJson(jsonString, ModelClass.class)

如果您想要您的常用函数作为其包装器:

fun <T> convertJsonToModel(jsonString: String, modelClass: Class<T>): T {
    val gson = Gson()
    return gson.fromJson(jsonString, modelClass)
}

此外,您还可以创建一个扩展函数,如下所示,

fun <T> String.toObject(targetClass: Class<T>): T {
val gson = Gson()
return gson.fromJson(this, targetClass)
}