Thread
#serialization
    why

    why

    1 year ago
    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

    1 year ago
    Assuming you want to serialize the list to json, you can do something like this:
    @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"}]
    why

    why

    1 year ago
    Hi thanks for your reply but this is not what I want exactly, given this
    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 :
    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]
    I wanna have my list supported just like the native ones : )
    the problem is that prebuilt collections serializers are internal : (
    given that, maybe there is another way of doing it without rewriting the whole thing?
    s

    sandwwraith

    1 year ago
    You can wrap your serializer around instance of prebuilt one. The classes are internal, but we have factory functions like
    ListSerializer(...)
    why

    why

    1 year ago
    back.. thanks a lot that’s what I was looking for : )