StringNumbers
and StringBooleans
Some external APIs, especially JSON-based ones, encode certain or all numbers, booleans and even null
as string values, even if the respective value could be represented as a native JSON or CBOR number, boolean or null
.
In order to make integration with these kind of services easy borer comes with predefined encoders and decoders for numbers, booleans and null
that you can “enable” with simple imports and which then take precedence over the default encoders and decoders.
This is how they are enabled:
sourceimport io.bullet.borer.{Decoder, Encoder}
import Encoder.StringNumbers.given // enables number-as-strings encoding
import Encoder.StringBooleans.given // enables booleans-as-strings encoding
import Encoder.StringNulls.given // enables null-as-strings encoding
import Decoder.StringNumbers.given // enables number-as-strings decoding
import Decoder.StringBooleans.given // enables booleans-as-strings decoding
import Decoder.StringNulls.given // enables null-as-strings decoding
As always these imports are “active” throughout the complete scope in which they are visible.
Here is an example demonstrating how to encode numbers and booleans as strings:
sourceimport io.bullet.borer.{Json, Encoder, Codec}
import io.bullet.borer.derivation.MapBasedCodecs.*
import Encoder.StringNumbers.given // enables number-as-strings encoding
import Encoder.StringBooleans.given // enables booleans-as-strings encoding
case class Dog(age: Int, male: Boolean, name: String) derives Codec
val dog = Dog(2, false, "Lolle")
// note how the Int and Boolean are rendered as JSON strings
Json.encode(dog).toUtf8String ==>
"""{"age":"2","male":"false","name":"Lolle"}"""
Decoding works correspondingly.
1.14.1