用于对象名称和值的 Play Framework JsReads

Play Framework JsReads for object names and values

考虑以下 JSON:

{
  "1992": "this is dog",
  "1883": "test string",
  "1732": "unknown",
  "2954": "future year"
}

有没有办法,用JSONreads把这个JSON改成Scala caseclass?即 Seq[Years]Map[String, String],其中 Year 包含年份和描述。

供参考,这是为 "simple" JSON 结构定义 read 的方式:

{
  "name": "george",
  "age": 24
}

隐式JsReads

implicit val dudeReads = (
    (__ \ "name").read[String] and
    (__ \ "age").read[Int]
) (Dude)

将您的 json 字符串转换为 JsValue,然后对 JsValue 对象使用验证。

scala> val json: JsValue = Json.parse("""
 | {
 |   "1992": "this is dog",
 |   "1883": "test string",
 |   "1732": "unknown",
 |   "2954": "future year"
 | }
 | """)
json: play.api.libs.json.JsValue = {"1992":"this is dog","1883":"test string","1732":"unknown","2954":"future year"}

scala> val valid = json.validate[Map[String,String]]
valid: play.api.libs.json.JsResult[Map[String,String]] = JsSuccess(Map(1992 -> this is dog, 1883 -> test string, 1732 -> unknown, 2954 -> future year),)

scala> valid match {
 | case s: JsSuccess[Map[String,String]] => println(s.get)
 | case e: JsError => println("Errors: " + JsError.toJson(e).toString())
 | }
Map(1992 -> this is dog, 1883 -> test string, 1732 -> unknown, 2954 -> future year)

类似于@Pranav 的回答,但更简洁:

Json.parse("""
    {
      "1992": "this is dog",
      "1883": "test string",
      "1732": "unknown",
      "2954": "future year"
    }
""").as[Map[String, String]]

产量

Map[String,String] = Map(1992 -> this is dog, 1883 -> test string, 1732 -> unknown, 2954 -> future year)

基础 Reads 被定义为 here