Hi, I wanna serialize a List<E> that I implemented, what is the right approach of doing it, using the prebuilt serializers (like ArrayListSerializer, ListLikeSerializer or even AbstractCollectionSerializer), I’m having so much trouble with these classes, can anyone help?
m
Mranders
10/09/2020, 7:48 AM
Assuming you want to serialize the list to json, you can do something like this:
Copy code
@Serializable
class E(val s: String)
fun main() {
val listOfEs = listOf(E("foo"), E("bar"), E("baz"))
val eListSerializer = ListSerializer(E.serializer())
val serialized = Json.Default.encodeToString(eListSerializer, listOfEs)
println(serialized)
}
Result: [{"s":"foo"},{"s":"bar"},{"s":"baz"}]
w
why
10/09/2020, 8:20 AM
Hi thanks for your reply but this is not what I want exactly, given this
Copy code
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
val listOfEs = listOf(1, 2, 34)
val serialized = Json.Default.encodeToString(listOfEs)
println(serialized) // result: [1,2,34]
I wanna be able to do this :
Copy code
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
val myList = MyListImplementation(1, 2, 34)
val serialized = Json.Default.encodeToString(myList)
println(serialized) // result: [1,2,34]
why
10/09/2020, 8:26 AM
I wanna have my list supported just like the native ones : )
why
10/09/2020, 8:30 AM
the problem is that prebuilt collections serializers are internal : (
why
10/09/2020, 8:31 AM
given that, maybe there is another way of doing it without rewriting the whole thing?
s
sandwwraith
10/09/2020, 8:59 AM
You can wrap your serializer around instance of prebuilt one. The classes are internal, but we have factory functions like
ListSerializer(...)
👍 1
w
why
10/09/2020, 9:56 AM
back.. thanks a lot that’s what I was looking for : )