Skip to content

Regression with serializing double values which could be represented as ints (e.g. 3.0) #2031

Description

@jschneider

#1937 introduced new behavior which seems to have regressions when serializing double values like 3.0.
When reading these values back, the type seems to have magically changed to int.

class JsonBsonEncoderNumberTypeReproducerTest {
  @Serializable
  private data class Container(val payload: JsonObject)

  @Test
  fun `JSON numbers keep their BSON type`() {
    //language=JSON
    val json = """{"integral": 3.0, "fractional": 15.9, "scientific": 1.0E20}"""
    val container = Container(Json.parseToJsonElement(json).jsonObject)

    val codec = KotlinSerializerCodec.create(
      Container::class,
      serializer<Container>(),
      EmptySerializersModule(),
      BsonConfiguration(),
    )

    val encoded = BsonDocument()
    codec.encode(BsonDocumentWriter(encoded), container, EncoderContext.builder().build())
    val decoded: Container = codec.decode(BsonDocumentReader(encoded), DecoderContext.builder().build())

    val payload: BsonDocument = encoded.getDocument("payload")
    assertEquals(BsonType.DOUBLE, payload.getValue("integral").bsonType) //FAILS: INT32
    assertEquals(BsonType.DOUBLE, payload.getValue("scientific").bsonType) //FAILS: DECIMAL128
    assertEquals(BsonType.DOUBLE, payload.getValue("fractional").bsonType)
    assertEquals(container, decoded) //FAILS: {"integral":3,"fractional":15.9,"scientific":1E+20}
  }
}

If course I have a much more complex use case. I am serializing Kotlin data classes with double properties.
But this should be the smallest possible reproducer for the issue.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions