Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Json.encode fails on Array[Byte] #40

Closed
mushtaq opened this issue Jun 29, 2019 · 2 comments
Closed

Json.encode fails on Array[Byte] #40

mushtaq opened this issue Jun 29, 2019 · 2 comments

Comments

@mushtaq
Copy link
Contributor

mushtaq commented Jun 29, 2019

Test

val bytes = "abc".getBytes()
Json.encode(bytes).toUtf8String

Error

io.bullet.borer.Borer$Error$Unsupported: The JSON renderer doesn't support byte strings (Output.ToByteArray index 0)

Related

All of the following works

Json.encode(bytes.head).toUtf8String
Cbor.encode(bytes.head).toByteArray
Cbor.encode(bytes).toByteArray

Workaround

implicit lazy val bytesEnc: Encoder[Array[Byte]] = targetSpecificEnc(
    cborEnc = Encoder.forByteArray,
    jsonEnc = Encoder.forArray[Byte]
  )

def targetSpecificEnc[T](cborEnc: Encoder[T], jsonEnc: Encoder[T]): Encoder[T] = { (writer, value) 
  val enc = if (writer.target == Cbor) cborEnc else jsonEnc
  enc.write(writer, value)
}

We had to write an analogous target specific decoder for Array[Bytes]

@sirthias
Copy link
Owner

sirthias commented Jul 12, 2019

How would you expect raw bytes to be encoded in JSON?
Base64 String? Simple hex string? As an array of JSON numbers?
IMHO there is no clear and valuable default strategy here, or is there?

@mushtaq
Copy link
Contributor Author

mushtaq commented Jul 13, 2019

@sirthias I agree that there is no natural default. But getting a runtime error is not nice.

For us, any default will work because we will rarely exercise this path when using the REST/Json.

I would suggest we go ahead with Encoder.forArray[Byte] as the default because that is what most JSON libs do.

Also, in this case encoder, we do not need to define the decoder, and the following works fine:
Json.decode(Json.encode("abc".getBytes()).toByteArray).to[Array[Byte]].value

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants