Mehedi Hassan Piash | Senior Software Engineer | Android | iOS | KMP | Ktor | Jetpack Compose | React-Native.

July 11, 2021

Json extension for kotlin

July 11, 2021 Posted by Piash , No comments
 // Transform simple object to String with Gson  
  fun <reified T : Any> T.toPrettyJson() : String = Gson().toJson(this, T::class.java)  
   
 // Transform String Json to Object   
 inline fun <reified T : Any> String.fromPrettyJson() : T = Gson().fromJson(this , T::class.java)  
   
 // Transform String List Json to Object   
 inline fun <reified T : Any> String.fromPrettyJsonList() : MutableList <T> = when( this.isNotEmpty()){  
     true -> Gson().fromJson(this, object : TypeToken<MutableList<T>>() {}.type)  
     false -> mutableListOf()  
 }  

0 comments:

Post a Comment