Last active
November 28, 2019 18:13
-
-
Save gavelez/eeb152d586e362e394e549bd22e390cb to your computer and use it in GitHub Desktop.
Use of Generics with Gson
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
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 | |
} | |
} |
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
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