Gson TypeToken with dynamic ArrayList item type

前端 未结 9 2177
情深已故
情深已故 2020-11-22 08:55

I have this code:

Type typeOfObjectsList = new TypeToken>() {}.getType();
List objectsList = new Gson().fromJso         


        
9条回答
  •  忘掉有多难
    2020-11-22 09:08

    With kotlin you can use a below functions to converting (from/to) any (JsonArray/JsonObject) just in one line without need to send a TypeToken :-

    Convert any class or array to JSON string

    inline fun  T?.json() = this?.let { Gson().toJson(this, T::class.java) }
    

    Example to use :

     val list = listOf("1","2","3")
     val jsonArrayAsString = list.json() 
     //output : ["1","2","3"]
    
     val model= Foo(name = "example",email = "t@t.com") 
     val jsonObjectAsString = model.json()
    //output : {"name" : "example", "email" : "t@t.com"}
    

    Convert JSON string to any class or array

    inline fun  String?.fromJson(): T? = this?.let {
        val type = object : TypeToken() {}.type
        Gson().fromJson(this, type)
    }
    

    Example to use :

     val jsonArrayAsString = "[\"1\",\"2\",\"3\"]"
     val list = jsonArrayAsString.fromJson>()
    
     val jsonObjectAsString = "{ "name" : "example", "email" : "t@t.com"}"
     val model : Foo? = jsonObjectAsString.fromJson() 
     //or 
     val model = jsonObjectAsString.fromJson() 
    

提交回复
热议问题