【问题标题】:Serialize Array[Array[Byte]] to Json将 Array[Array[Byte]] 序列化为 Json
【发布时间】:2014-09-28 18:48:13
【问题描述】:

我有一个 Array[Array[Byte]],我想在 Playframework 中将它序列化为 Json:

implicit val matrixWrites = new Writes[matrix] {
    def writes(c: Matrix): JsValue = {
  Json.obj(
        "id" -> c.id,
        "matr" -> c.matr
      )
    }
  }

但是我得到错误Type mismatch: found (String, Array[Array[Byte]] required (String, Json.JsValueWrapper)

将 Array[Array[Byte]] 转换为 Json 的正确方法是什么?

【问题讨论】:

标签: scala playframework


【解决方案1】:

创建一个Writes[Array[Array[Byte]]],将字节数组的数组序列化为某种字符串格式(可能是 base64 )。

您可能还想为相同类型创建一个Reads 以转换回Array[Array[Byte]]

【讨论】:

    【解决方案2】:

    在相关说明中,我喜欢包装我的二进制数据,因此不必显式导入隐式格式。

    import org.apache.commons.codec.binary.Base64
    import play.api.libs.json.{Format, Reads, Writes}
    
    case class BinaryData(bytes: Array[Byte])
    
    object BinaryData {
        implicit val MessageFormat: Format[BinaryData] = Format(Reads.of[String].map(s => apply(Base64.decodeBase64(s))), Writes(a => Writes.of[String].writes(Base64.encodeBase64String(a.bytes))))
    }
    

    【讨论】:

    • 这似乎不是一个答案。如果您试图对问题或答案发表评论,请尽您所能。
    猜你喜欢
    • 2019-04-04
    • 2014-07-21
    • 2021-12-21
    • 2023-01-21
    • 2014-04-18
    • 2013-06-26
    • 1970-01-01
    • 2020-01-08
    • 1970-01-01
    相关资源
    最近更新 更多