Skip to content
Snippets Groups Projects
Commit 26750845 authored by Kamal Bramwell's avatar Kamal Bramwell
Browse files

Added TypeTokens to Gson decoding

parent e0e46a0a
No related branches found
No related tags found
No related merge requests found
...@@ -16,14 +16,19 @@ interface BindingsModel { ...@@ -16,14 +16,19 @@ interface BindingsModel {
val data = list.map { val data = list.map {
(it as? ByteArray)?.toBase64String() ?: it (it as? ByteArray)?.toBase64String() ?: it
} }
return Gson().toJson(data.toTypedArray(), Array<T>::class.java).encodeToByteArray() return Gson().toJson(
data.toTypedArray(),
object : TypeToken<Array<T>>() {}.type
).encodeToByteArray()
} }
inline fun <reified T> decode(data: ByteArray?): T? { inline fun <reified T> decode(data: ByteArray?): T? {
return data?.run { return data?.run {
if (isValidData()) { if (isValidData()) {
val typeToken = object : TypeToken<T>() {}.type Gson().fromJson<T>(
Gson().fromJson<T>(decodeToString(), typeToken) decodeToString(),
object : TypeToken<T>() {}.type
)
} else { } else {
Log.d("Decode", "Failed to decode data: ${decodeToString()}") Log.d("Decode", "Failed to decode data: ${decodeToString()}")
null null
...@@ -34,8 +39,10 @@ interface BindingsModel { ...@@ -34,8 +39,10 @@ interface BindingsModel {
inline fun <reified T> decodeArray(data: ByteArray?): List<T> { inline fun <reified T> decodeArray(data: ByteArray?): List<T> {
return data?.run { return data?.run {
if (isValidData()) { if (isValidData()) {
val typeToken = object : TypeToken<Array<T>>() {}.type Gson().fromJson<Array<T>>(
Gson().fromJson<Array<T>>(decodeToString(), typeToken).toList() decodeToString(),
object : TypeToken<Array<T>>() {}.type
).toList()
} else listOf() } else listOf()
} ?: listOf() } ?: listOf()
} }
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment