jsoniter-scala icon indicating copy to clipboard operation
jsoniter-scala copied to clipboard

Question: Is there a way to make the value of the discriminator field snake case

Open bizzard4 opened this issue 8 months ago • 1 comments

We are moving one of our endpoint to use jsoniter for performance reason. We are trying the not change the existing format of the json because it already publish to some client. For the most we were able to align the format but we have an issue with the value of the type discriminator field. The value is in snake case but the decoder only take normal case.

I made a small ShapeRequest example to demonstrate

sealed trait Shape
object Shape {
  case class ComplexShape(faceCount: Int) extends Shape
}

case class ShapeRequest(
  shape: Shape,
                       )
object ShapeRequest {
  @annotation.nowarn
  implicit val fastCodec: JsonValueCodec[ShapeRequest] =
    JsonCodecMaker.make[ShapeRequest](CodecMakerConfig
      .withFieldNameMapper(JsonCodecMaker.enforce_snake_case)
      .withUseScalaEnumValueId(true))

  implicit val tapirJsoniterCodec: sttp.tapir.Codec[String, ShapeRequest, CodecFormat.Json] =
    new sttp.tapir.Codec[String, ShapeRequest, CodecFormat.Json] {
      override def rawDecode(l: String): DecodeResult[ShapeRequest] =
        DecodeResult.Value(readFromString[ShapeRequest](l))
      override def encode(h: ShapeRequest): String = writeToString(h)
      override def schema: Typeclass[ShapeRequest] =
        schemaForCaseClass[ShapeRequest].value
      override def format: CodecFormat.Json = CodecFormat.Json()
    }
}

This ShapeRequest get serialized into. It all good but the ComplexShape that we would like to be snake case.

{"shape":{"type":"ComplexShape","face_count":10}}

Is there a way to encode/decode the type value in snake case. Ie. "type": "complex_shape"

bizzard4 avatar Mar 03 '25 18:03 bizzard4