Json 要映射的对象

Json object to map

您好,我想使用隐式读取将 json 对象转换为地图。 使用下面的代码我 运行 进入 Whosebug 错误,任何人都可以看出问题所在:

"pass": {
  "key-1": {
    "field1": "aaaa",
    "field2": "aaaa"
  },
  "key-2": {
    "field1": "aaaa",
    "field2": "aaaa"
  },
  "key-3": {
    "field1": "aaaa",
    "field2": "aaaa"
  }
}

case class Pass(field1: String, field2: String)

implicit val mapReads: Reads[Map[String, Pass]] = new Reads[Map[String, Pass]] {
  def reads(jv: JsValue): JsResult[Map[String, Pass]] =
    JsSuccess(jv.as[Map[String, Pass]].map{
      case (k, v) => k -> v.asInstanceOf[Pass]
    })
}

val passMap = (json \ "pass").validate[Map[String, Pass]]

这是堆栈错误:

java.lang.WhosebugError
  at play.api.libs.json.JsReadable$class.as(JsReadable.scala:23)
  at play.api.libs.json.JsObject.as(JsValue.scala:124)
  at com.MyHelper$$anon.reads(MyHelper.scala:51)
  at play.api.libs.json.Format$$anon.reads(Format.scala:65)
  at play.api.libs.json.JsValue$class.validate(JsValue.scala:17)
  at play.api.libs.json.JsObject.validate(JsValue.scala:124)
  at play.api.libs.json.JsReadable$class.as(JsReadable.scala:23)
  at play.api.libs.json.JsObject.as(JsValue.scala:124)

也许您更有可能创建一个 MapPass class 案例并使用 Json.format 为您完成工作!

import play.api.libs.json._

val a: String = """{
  "pass": {
    "key-1": {
    "field1": "aaaa",
    "field2": "aaaa"
  },
    "key-2": {
    "field1": "aaaa",
    "field2": "aaaa"
  },
    "key-3": {
    "field1": "aaaa",
    "field2": "aaaa"
  }
  }
}"""

case class Pass(field1: String, field2: String)

case class MapPass(pass: Map[String, Pass])

implicit val passFormat: Format[Pass] = Json.format[Pass]
implicit val mapPassFormat: Format[MapPass] = Json.format[MapPass]

val json = Json.parse(a)
val mapPassJsResult = json.validate[MapPass]
val mapPass = mapPassJsResult.get
print(mapPass.pass.mkString("\n"))

对我来说就是这样: