我有下面的案例类
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]编写编解码器。我查看了在线文档,但它仍然在TODO中。
你知道怎么写Map[String, String]的编解码器吗?
发布于 2020-03-24 03:28:04
您需要做的是为字符串元组定义Codec,然后您将需要使用它为List[(String, String)]创建编解码器,该编解码器可以转换为Map[String, String],反之亦然,因此使用xmap函数隐藏Codec。
因此,最终的解决方案可能如下所示:
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]希望这能有所帮助!
https://stackoverflow.com/questions/60819654
复制相似问题