Thread
#serialization
    Peter

    Peter

    10 months ago
    hi - does anyone know how to encode constants to json? eg
    data class Test(val a: String) {
      val b: String = "alwaysthesame"
    }
    i’m looking for
    Test("x")
    to be
    {"a": "x", "b": "alwaysthesame"}
    looks like private constructor with all the fields and public constructor with limited fields is the only way
    p

    Paul Griffith

    10 months ago
    or a custom serializer
    kotlinx-serialization is fairly opinionated, but it's pretty uncommon in serialization frameworks to encode a default value for space concerns
    b

    Ben Woodworth

    10 months ago
    Does this work?
    data class Test(val a: String) {
      val b: String
    
      init {
        b = "alwaysthesame"
      }
    }
    I think it might not be encoding because encodeDefaults is false, and b has the default value "alwaysthesame"
    If it does work, you could also do this in kotlinx.serialization 1.3.0:
    @EncodeDefault
    val b: String = "alwaysthesame"