sirthias / borer

Efficient CBOR and JSON (de)serialization in Scala
https://sirthias.github.io/borer/
Mozilla Public License 2.0
224 stars 14 forks source link

Cannot serialize BigDecimal value with a fractional part #22

Closed plokhotnyuk closed 5 years ago

plokhotnyuk commented 5 years ago
scala> io.bullet.borer.Json.encode(BigDecimal(100)).toByteArray
res0: Array[Byte] = Array(49, 48, 48)

scala> io.bullet.borer.Json.encode(BigDecimal(100.1)).toByteArray
io.bullet.borer.Borer$Error$Unsupported: The JSON renderer doesn't support CBOR tags [Output.ToByteArray index 0]
  at io.bullet.borer.json.JsonRenderer.failUnsupported(JsonRenderer.scala:279)
  at io.bullet.borer.json.JsonRenderer.onTag(JsonRenderer.scala:221)
  at io.bullet.borer.Writer.writeTag(Writer.scala:67)
  at io.bullet.borer.Encoder$.$anonfun$forJBigDecimal$1(Encoder.scala:130)
  at io.bullet.borer.Encoder$EncoderOps$.$anonfun$contramap$1(Encoder.scala:80)
  at io.bullet.borer.Writer.write(Writer.scala:86)
  at io.bullet.borer.EncodingSetup$Impl.render(EncodingSetup.scala:165)
  at io.bullet.borer.EncodingSetup$Impl.bytes(EncodingSetup.scala:113)
  at io.bullet.borer.EncodingSetup$Impl.toByteArray(EncodingSetup.scala:101)
  ... 36 elided

W/A is to add a custom encoder:

scala> implicit val bigDecimalEnc: io.bullet.borer.Encoder[BigDecimal] = io.bullet.borer.Encoder.apply[BigDecimal]((w, x) => w.writeNumberString(x.bigDecimal.toString))
bigDecimalEnc: io.bullet.borer.Encoder[BigDecimal] = $$Lambda$6643/1040047064@37e72351

scala> io.bullet.borer.Json.encode(BigDecimal(100.1)).toByteArray
res1: Array[Byte] = Array(49, 48, 48, 46, 49)
sirthias commented 5 years ago

Yup. Thank you!