I am needing our GSON parser to be able to handle an array vs single objects. I've got it working to where it recognizes any MutableList and falls into the Deserializer adapter below. However, I'm missing a piece where it's not liking the "T" type when actually doing the serialization into an object. I understand that it needs the type at this point, but is there something I'm missing to be able to infer this given what we have here?
class JsonArrayObjectAdapter<T>: JsonDeserializer<MutableList<T>> {
override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): MutableList<T> {
val list = mutableListOf<T>()
json?.let {
context?.let {
if (json.isJsonArray) {
for (element in json.asJsonArray) {
val obj: T = context.deserialize(element, T::class.java) // does not like this
list.add(obj)
}
} else if (json.isJsonObject) {
val obj: T = context.deserialize(json, T!!::class.java) // does not like this
list.add(obj)
}
}
}
return list
}
}
I get this compile error when trying to use T::class.java
:
Cannot use 'T' as reified type parameter. Use a class instead.
Here's an example of a data class I'm using, for reference:
data class ExampleDataClass(
@SerializedName("ExampleKey") val exampleVar: MutableList<ExampleSubDataClass>
)
And here is how I do the gson creation:
val listType = object : TypeToken<MutableList<ExampleDataSubClass>>() {}.getType()
val gson = GsonBuilder()
.registerTypeAdapter(listType, JsonArrayObjectAdapter<ExampleDataSubClass>())
.create()
result = gson.fromJson(jsonString, ExampleDataClass::class.java)