简体   繁体   English

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

[英]How to write scodec codec for Collection Map

I have below case class我有以下案例类

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

Below is the code that I've tried so far -以下是我迄今为止尝试过的代码 -

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]

I don't know how to write Codec for Map[String, String] .我不知道如何为Map[String, String]编写编解码器。 I checked online documentation but it is still in TODO.我检查了在线文档,但它仍在 TODO 中。

Any idea how can I write the codec for Map[String, String] ?知道如何为Map[String, String]编写编解码器吗?

What you would need to do is to define Codec for tuple of strings, which then you will need to use to create codec for List[(String, String)] which can be converted to Map[String, String] and vice versa, hence covert Codec using xmap function.您需要做的是为字符串元组定义Codec ,然后您需要使用它为List[(String, String)]创建编解码器,它可以转换为Map[String, String] ,反之亦然,因此使用xmap函数的隐蔽Codec

So the final solution might look like:所以最终的解决方案可能如下所示:

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]

Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM