Skip to content

Instantly share code, notes, and snippets.

@gavelez
Last active November 28, 2019 18:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gavelez/eeb152d586e362e394e549bd22e390cb to your computer and use it in GitHub Desktop.
Save gavelez/eeb152d586e362e394e549bd22e390cb to your computer and use it in GitHub Desktop.
Use of Generics with Gson
package com.example.util
import com.example.MyList
class CollectionWrapper<T> {
var type: Class<T>
var list: MyList<T>
constructor(valueType: Class<T>, list: MyList<T>) {
type = valueType
this.list = list
}
}
package com.example.util
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.example.IConverter
import com.example.ProductQuantity
import com.example.ProductSoldQuantity
import com.example.MyList
class JsonConverter : IConverter {
override fun <T : Any?> writeValue(src: ByteArray?, valueType: Class<T>?): T =
Gson().fromJson(src?.let { String(it) }, valueType)
override fun writeValueAsBytes(value: Any?): ByteArray {
return if (value !is CollectionWrapper<*>) {
Gson().toJson(value).toByteArray()
} else {
when (value.type) {
ProductSoldQuantity::class.java -> {
val type = object : TypeToken<WingoList<ProductSoldQuantity>>() {}.type
Gson().toJson(value.list, type).toByteArray()
}
ProductQuantity::class.java -> {
val type = object : TypeToken<WingoList<ProductQuantity>>() {}.type
Gson().toJson(value.list, type).toByteArray()
}
else -> ByteArray(0)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment