Kotlinx.serialization: Deserialize a list of generics inside a data class

Created on 10 Apr 2020  Â·  7Comments  Â·  Source: Kotlin/kotlinx.serialization

Say you have:

@Serializable
data class PagedData<T>(val data: T, val page: Int, val totalPages: Int, val pageSize: Int)

Where you know for sure that T is a class that has the annotations @Serializable or a list of a type that is annotated with @Serializable.

Why the serialization runtime is not able to infer what to use? Also, I am using Ktor, it would be kind of pointless to explicitly build a serializer before every response as such.

feature ktor

Most helpful comment

Please never use Gson.

  – Signed, a Gson mainterner.

All 7 comments

In general, the answer is 'that's hard' because of JVM generics erasure. To overcome that, one may need to explicitly build serializer, as you stated. Indeed, it is not very handy in the case of ktor or another framework. I think ktor should support capturing a Java's type token (which stores generic information) and then produce the correct serializer out of it, but I don't know if this feature is implemented already.

So what should I do, move to GSON? 🤣 I'd rather not, but still , the issue is real

Please never use Gson.

  – Signed, a Gson mainterner.

Hi @lamba92, what is your version of ktor?

Please never use Gson.

  – Signed, a Gson mainterner.

😆 Fair enough! I won't!

Hi @lamba92, what is your version of ktor?

Ktor 1.3.2, Kotlin 1.3.71

Failed to reproduce it locally. Could you show how you make the request?

Here!

Actually it is a serialization error, I haven't tried deserialization yet.

kotlinx.serialization.SerializationException: Can't locate argument-less serializer for class PagedData. For generic classes, such as lists, please provide serializer explicitly.
Was this page helpful?
0 / 5 - 0 ratings

Related issues

sandwwraith picture sandwwraith  Â·  4Comments

lonevetad picture lonevetad  Â·  3Comments

ersin-ertan picture ersin-ertan  Â·  3Comments

kdabir picture kdabir  Â·  3Comments

kastork picture kastork  Â·  3Comments