I get a JSON data model that has a map wrapper table. I am trying to use generics to pass in a type that is outside the shell, but it does not translate well at runtime. Here is an example of my JSON file:
{ "Table": [ { "paymentmethod_id": 1, "paymentmethod_description": "Cash", "paymentmethod_code": "Cash", "paymentmethod_is_ach_onfile": false, "paymentmethod_is_element": false, "paymentmethod_is_reward": false, "paymentmethod_is_openedgeswipe": false, "paymentmethod_update_user_id": 1, "paymentmethod_insert_user_id": 1, "paymentmethod_insertdate": "2014-10-07 14:53:16", "paymentmethod_deleted": false, "paymentmethod_is_mobile_visible": true } ] }
The wrapper class I'm using is called Table.
data class Table<T>( @SerializedName("Table") val models : Array<T> )
The actual model class is PaymentMethod.
data class PaymentMethod( @SerializedName("paymentmethod_id") val idNumber : Int = -1 )
I created a generic data manager class that accepts <T>. I think using subclasses of the data manager to localize input and results (for example, declaring a PaymentMethod model class.
open class NXDataManager<T>(manager: NXNetworkManager? = null, rpc : String?, parameters: List<Pair<String, String>>? = null, method : String = "get") { ... open fun sendRequest(completionHandler: (models:Array<T>) -> Unit, errorHandler: (error:FuelError) -> Unit) { val request = NXNetworkRequest(rpc, parameters, method) request.send(manager, completionHandler = { s: String -> val table: Table<T> = Gson().fromJson(s) completionHandler(table.models) }, errorHandler = errorHandler) } inline fun <reified T> Gson.fromJson(json: String) = this.fromJson<T>(json, object: TypeToken<T>() {}.type) }
My subclass data manager defines a model for analysis.
final public class PaymentMethodsDataManager : NXDataManager<PaymentMethod> { constructor () : super("genGetPaymentMethods") }
When I run the code like:
val table: Table<T> = Gson().fromJson(s)
I get the error java.lang.ClassCastException: java.lang.Object [] could not be passed to Networking.PaymentMethod [] . However, when I pass an explicit type, it works as expected - parsing the array in PaymentMethod models:
val table: Table<PaymentMethod> = Gson().fromJson(s)
Any ideas on how I can use generic type T?