Last active
March 14, 2023 06:33
-
-
Save adfleshner/8ad443b52a45c7ce0a61b703d639b880 to your computer and use it in GitHub Desktop.
Gson Kotlin Extensions. I created a few simple extensions for gson to Simplfy any Gson needs.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.gson.Gson | |
import com.google.gson.GsonBuilder | |
import com.google.gson.reflect.TypeToken | |
val gson: Gson = GsonBuilder().create() | |
val gsonPretty: Gson = GsonBuilder().setPrettyPrinting().create() | |
inline fun <reified T> T.toJson(prettyPrint : Boolean = false) :String{ | |
return if(prettyPrint){ | |
gsonPretty | |
}else { | |
gson | |
}.toJson(this) | |
} | |
inline fun <reified T> String.fromJson() : T { | |
return gson.fromJson(this,T::class.java) | |
} | |
inline fun <reified T> String.fromListJson() : List<T> { | |
val listType = object: TypeToken<List<T>>(){}.type | |
return gson.fromJson(this, listType) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data class User(val name :String, val username: String) | |
import org.junit.Test | |
class GsonTest { | |
@Test | |
fun `Gson toJson extension works`(){ | |
val user = User("Aaron","adfleshner") | |
val actual = user.toJson() | |
println(actual) | |
assert(actual is String) | |
} | |
@Test | |
fun `Gson toJson list extension works`(){ | |
val user = listOf(User("Aaron","adfleshner")) | |
val actual = user.toJson() | |
println(actual) | |
assert(actual is String) | |
} | |
@Test | |
fun `Gson fromJson extension works`(){ | |
val str = "{\"name\":\"Aaron\",\"username\":\"adfleshner\"}" | |
val user = str.fromJson<User>() | |
assert(user is User) | |
} | |
@Test | |
fun `Gson fromListJson extension works`(){ | |
val str = "[{\"name\":\"Aaron\",\"username\":\"adfleshner\"}]" | |
val users = str.fromListJson<User>() | |
assert(users is List<User>) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
implementation 'com.google.code.gson:gson:2.10.1'