如何为Collection Map编写scodec编解码器

时间:2020-03-23 18:36:35

标签: scala scodec

我有以下案例课

case class Foo(code: Int, msg: String, headers: Map[String,String] = Map.empty)

下面是到目前为止我尝试过的代码-

import scodec._
import scodec.codecs._

implicit val mapCodec: Codec[List[(String, String)]] = sizedList()

implicit val fooCodec : Codec[Foo] = {
    ("code" | int32) :: ("msg" | cstring) :: ("headers" | mapCodec)
}.as[Foo]

我不知道如何为Map[String, String]编写Codec。我检查了在线文档,但仍在TODO中。

知道如何为Map[String, String]编写编解码器吗?

1 个答案:

答案 0 :(得分:3)

您需要做的是为字符串元组定义Codec,然后您将需要使用它来为List[(String, String)]创建编解码器,并将其转换为Map[String, String]反之亦然,因此使用Codec函数隐蔽xmap

所以最终的解决方案可能看起来像:

import scodec._
import scodec.codecs._
case class Foo(code: Int, msg: String, headers: Map[String,String] = Map.empty)

implicit val tupleCodec : Codec[(String, String)] = cstring.pairedWith(cstring)
implicit val mapCodec: Codec[Map[String, String]] = list(tupleCodec).xmap(_.toMap, _.toList)

implicit val fooCodec : Codec[Foo] = {
  ("code" | int32) :: ("msg" | cstring) :: ("headers" | mapCodec)
}.as[Foo]

希望这会有所帮助!

相关问题