https://kotlinlang.org logo
#serialization
Title
# serialization
a

Albert

08/16/2018, 9:49 AM
I am a bit lost. I am trying to make a custom KSerializer for an object which is a third party entity. Effectively I want to achieve writing
Map<String, Any>
but I can't not find how. I tried a specific implementation for that particular class like so:
Copy code
output.write(
                (StringSerializer to StringSerializer).map,
                mapOf(
                        "access_token" to obj.accessToken,
                        "token_type" to obj.tokenType
                )
        )

        output.write(
                (StringSerializer to IntSerializer).map,
                mapOf(
                        "expires_in" to obj.expiresIn
                )
        )
But this results into 2 JSON documents. I have the feeling I am overlooking a particular
Serializer
s

sandwwraith

08/16/2018, 10:18 AM
write
writes top-level object. You need to use
writeBegin
and then write elements one-by-one using methods which accept
index
a

Albert

08/16/2018, 11:01 AM
Now I get an Index 0 out-of-bounds for length 0 exception:
Copy code
override val serialClassDesc: KSerialClassDesc
        get() = SerialClassDescImpl(TokenResponse::class.qualifiedName!!)

    override fun load(input: KInput): TokenResponse {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun save(output: KOutput, obj: TokenResponse) {

        output.writeBegin(serialClassDesc)

        output.writeStringElementValue(
                serialClassDesc,
                0,
                "test_obj"
        )

        output.writeEnd(serialClassDesc)
        
    }
From what I can find it looks it has something todo with the
@SerialId(1)
not being present on the entity. But I can't do this because it is in an external module
s

sandwwraith

08/16/2018, 11:09 AM
you need to fill in
SerialClassDescImpl
with
addElement
according to number of indices you want to write
a

Albert

08/16/2018, 11:15 AM
Works like a charm. Thanks @sandwwraith
8 Views