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

Nick

11/16/2023, 9:18 PM
For some reason I can't get serialization to encode a string when it's assigned from the value of an enum. It works fine when I assign the string from a different string, or if i append string to the enum's value. See 🧵
Copy code
@Serializable
data class ContactQR(
    val did: String? = null,
    val displayName: String,
    val type: String,
    val thid: String? = null,
)


val type: String = ContactType.Personal.value // the assigns the word "Personal" to `type`
val contactQR = ContactQR(
    did = userIdentity.did,
    type = type,
    displayName = profile.displayName,
)
Json.encodeToString(contactQR).also {
    println("QR code: $it")
}
Output
Copy code
{
  "did": "did:evan:EiDBY2wGCWTQu3GzNXjHvAfTti009q5vNhOaPVKTp4iesw",
  "displayName": "office space"
}
Copy code
val type: String = ContactType.Personal.value + "asdf"
val contactQR = ContactQR(
    did = userIdentity.did,
    type = type,
    displayName = profile.displayName,
)
Json.encodeToString(contactQR).also {
    println("QR code: $it")
}
Output
Copy code
{
  "did": "did:evan:EiDBY2wGCWTQu3GzNXjHvAfTti009q5vNhOaPVKTp4iesw",
  "displayName": "office space",
  "type": "Personalasdf"
}
e

ephemient

11/16/2023, 11:46 PM
does that match a default value in the class? if so, you need
@EncodeDefault
or
Copy code
Json { encodeDefaults = true }
to see it in the output
n

Nick

11/16/2023, 11:46 PM
@ephemient that was exactly the issue.
thanks