Skip to content

GsonUtils

Jacob Rein edited this page May 7, 2020 · 4 revisions

implementation 'com.github.jakepurple13.HelpfulTools:gsonutils:{version}'

Super easy way to convert objects to json and json string's to objects!

To use:

data class AnotherObject(val item: String)
data class GsonObject(val string: String, val int: Int, val anotherObject: AnotherObject)

val item = GsonObject("Hello", 5, AnotherObject("World"))
val jsonString: String = item.toJson()
val jsonPrettyString: String = item.toPrettyJson()
val gsonObject: GsonObject = jsonString.fromJson<GsonObject>()

Also added a couple other functions for Intents and SharedPreferences:

val intent = Intent(/*...*/).apply {
   putExtra("key", item)
}
val item2 = intent.getObjectExtra<GsonObject>("key", null)

getSharedPreferences("SharedPreferences", Context.MODE_PRIVATE).edit().putObject("gson", item).apply()
val item3 = getSharedPreferences("SharedPreferences", Context.MODE_PRIVATE).getObject<GsonObject>("gson")

Along with some network methods:

val string = getApi("api url")
val apiObject = getJsonApi<GsonObject>("api url")

Also added a method to tie in with the SharedPrefDelegate called sharedPrefObjectDelegate:

var Context.gsonObject: GsonObject? by sharedPrefObjectDelegate()
Clone this wiki locally