Reputation: 23
I've been searching a way to change Scala's Array[Byte] to some other immutable collection class. I'd like to refactor those said bytearrays to a more elegant Akka ByteStrings, however I've ran into a problem with encoding. As far as I know (I'm a scala newbie) encoding ByteStrings and Array[Bytes] with Jackson serialization returns different results for both datatypes using same values using Base64. So my question is, is there a nice and clean way to refactor Arrays to immutable collections while keeping the same Base64 serialized values as the old Array had?
Upvotes: 2
Views: 1082
Reputation: 4296
I'd use circe or argonaut instead of Jackson for the json serialization. They easily allow you to provide a custom encoder for different types.
implicit val byteArrayEncoder =
Encoder.encodeString.contramap[Array[Byte]](new String(_))
implicit val byteStringEncoder =
Encoder.encodeString.contramap[ByteString](_.UTF_8)
Then you can use it like ..
import io.circe._, io.circe.generic.auto._, io.circe.parser._, io.circe.syntax._
case class Whatever(bytes: Array[Byte], bstring: ByteString)
Whatever(???).asJson.nospaces
for more see
https://circe.github.io/circe/
Upvotes: 2