【问题标题】:Scala circe decode Map[String, String] typeScala circe 解码 Map[String, String] 类型
【发布时间】:2019-03-15 18:31:45
【问题描述】:

我有一个想要用作 json 的 Map[String, String] 对象。我已经为这种类型编写了一个编码器:

implicit val encodeMap: Encoder[Map[String, String]] = new Encoder[Map[String, String]] {
override def apply(values: Map[String, String]): Json = {
  values.toList
    .map(pair => Json.obj(
      (pair._1, pair._2.asJson)
    )).asJson
}
}

除了编码器,我还需要一个解码器,但我不知道如何编写它。到目前为止我最好的尝试:

implicit val decodeMap: Decoder[Map[String, String]] = new Decoder[Map[String, String]] {
final def apply(c: HCurser): Decoder.Result[Map[String, String]] = ???

}

相当基本,但我真的不知道如何解决这个问题。
谢谢!

【问题讨论】:

  • import io.circe.generic.auto._ 不只是在这里工作吗(允许你使用.asJson)?

标签: scala circe


【解决方案1】:

这样的事情应该可以,但正如 Andy 上面所说,在这种情况下,您应该能够使用自动或半自动推导。

import cats.syntax.either._

implicit val decodeMap: Decoder[Map[String, String]] = new Decoder[Map[String, String]] {
  override def apply(c: HCursor): Decoder.Result[Map[String, String]] = {
    c.keys.fold[Decoder.Result[Map[String, String]]](Right(Map.empty))(
      _.foldLeft(Map[String, String]().asRight[DecodingFailure])((res, k) => {
        res.flatMap((m: Map[String, String]) => {
          c.downField(k).as[String].fold(
            _.asLeft[Map[String, String]],
            v => (m + (k -> v)).asRight[DecodingFailure]
          )
        })
      })
    )
  }
}

【讨论】:

猜你喜欢
  • 2020-10-28
  • 2019-05-31
  • 2018-12-24
  • 2020-09-17
  • 2018-03-22
  • 2016-07-21
  • 2019-03-13
  • 2017-05-08
  • 1970-01-01
相关资源
最近更新 更多