Kotlin var does not save generic type (deserialized to LinkedTreeMap instead)
See original GitHub issuedata class BigClass(var inBig: Map<String, List<SmallClass>>? = null)
data class SmallClass(var inSmall: String? = null)
fun main(args: Array<String>) {
val json = """
{
"inBig": {
"key": [
{ "inSmall": "hello" }
]
}
}
"""
val deserialized = Gson().fromJson(json, BigClass::class.java)
println(deserialized.inBig!!["key"]!![0].inSmall) // should print "hello" but throws instead
}
Executing the code above will lead to the following Exception:
Exception in thread "main" java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to SmallClass
at MyClass.main(MyClass.kt:18)
The List<SmallClass>
is actually deserialized to List<LinkedTreeMap>
.
However, if I changed the definition of inBig
variable to be a constant, then it deserializes just fine:
data class BigClass(val inBig: Map<String, List<SmallClass>>? = null)
I changed var
to val
and the code prints “hello” as expected.
Kotlin 1.1.1 and Gson 2.8.1.
Issue Analytics
- State:
- Created 6 years ago
- Reactions:11
- Comments:11 (7 by maintainers)
Top Results From Across the Web
Convert to custom class using GSON and Generics with Kotlin ...
It don't understand that i want convert to Todo class instead of LinkedTreeMap. The code is here: https://github.com/xplpc/xplpc/blob/main/ ...
Read more >Parsing json into Java Pojos with Gson called from Kotlin is ...
I'm having an issue with Java types and Gson, when being called ... See Kotlin var does not save generic type (deserialized to...
Read more >Android/Kotlin Series: [#04] — How to use TypeToken + ...
T is a generic type that will be inferred from the call when you use the method. Hence you don't need to explicitly...
Read more >Convert JSON to a Map Using Gson - Baeldung
And, due to type erasure, we won't be able to configure this coercion ... for the generic types, Gson has an overloaded version...
Read more >Gson serialize generic type, Com Google Gson internal ...
This example shows how to serialize and deserialize a generic class using GSON. ... LinkedTreeMap cannot be cast to Kotlin var does not...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
after adding in data class
@JvmSuppressWildcards(suppress = true)
to problematic field I still getLinkedTreeMap
yep, you probably want
@JvmSuppressWildcards
. https://github.com/google/dagger/issues/668#issuecomment-289713497