[英]How to write scodec codec for Collection Map
我有以下案例类
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]
编写编解码器吗?
您需要做的是为字符串元组定义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]
希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.