如何通过忽略fieldname区分大小写来解码scala中的json

时间:2017-04-11 11:02:35

标签: json scala circe

我有以下失败的测试用例:

case class ActionRequest(action: String, `type`:String, key: String)

"Actions " should " be decoded correctly" in {
    val actionJson =
      """[
        |{"Action":"view","Type":"Product","Key":"1210"},
        |{"action":"filter","type":"by-price","key":"low-hi"}
        |]
        |""".stripMargin
    val actions = decode[List[ActionRequest]](actionJson).right.getOrElse(List())
    assert(actions.size == 2)
}

解码失败,错误:

LeftProjection(Left(DecodingFailure([A]List[A], List(DownField(action), DownArray))))

解码器是否可以映射忽略区分大小写的字段? 或者也许有一种优雅的方式使用decoder.prepare来处理它?<​​/ p>

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以尝试以下代码:

import io.circe._
import io.circe.generic.auto._

object CirceApp extends App {

    val actionJson = """[
      {"Action":"view","Type":"Product","Key":"1210"},
      {"action":"filter","type":"by-price","key":"low-hi"}
    ]""".stripMargin

    case class ActionRequest(action: String, `type`: String, key: String)

    implicit val decodeActionJson: Decoder[ActionRequest] = (c: HCursor) => {
        val keysMapping = c.keys.get.groupBy(_.toLowerCase).map(kv => (kv._1, kv._2.head))
        for {
            actionField <- c.downField(keysMapping("action")).as[String]
            typeField <- c.downField(keysMapping("type")).as[String]
            keyField <- c.downField(keysMapping("key")).as[String]
        } yield {
          ActionRequest(actionField, typeField, keyField)
        }
    }

    println(decode[Seq[ActionRequest]](actionJson))
}