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

zt

02/08/2023, 10:04 PM
Copy code
@Serializable
data class Teaser(
    val text: Text
) {
    @Serializable
    data class Text(val content: String)
}
How can I get rid of the boxing of text and be able to use it just like a string?
a

Adam S

02/08/2023, 10:58 PM
Copy code
@Serializable
@JvmInline
value class Text(val content: String)
do you mean like a value class? then you can do
Copy code
Json.decodeFromString<Teaser>("""
{
  "text": "blah blah"
}
""")
z

zt

02/08/2023, 11:50 PM
I wanna be able to decode this
Copy code
{
  "text": {
    "content": "g"
  }
}
to this
Copy code
Teaser(text=g)
m

Mitchell Syer

02/09/2023, 1:54 AM
Copy code
@Serializable
data class Teaser(
    @SerialName("text")
    val textObj: Text
) {
    constructor(text: String) : this(Text(text))

    @Transient // not sure if this is needed
    val text: String
        get() = textObj.content

    @Serializable
    data class Text(val content: String)
}
z

zt

02/09/2023, 2:51 AM
isn't this for just serializing? I only need deserializing
m

Mitchell Syer

02/09/2023, 2:52 AM
The
Serializable
annotation is for both serializing and deserializing
If you don't need serializing you can remove the secondary constructor from the code I posted
3 Views