1

考虑以下 JSON:

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

有什么办法,使用 JSONreads将这个 JSON 转换为 Scala 案例类?即 aSeq[Years]或 a Map[String, String],其中a Year 包含年份和描述。

作为参考,这是read为“简单”JSON 结构定义的方式:

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

隐含的JsReads

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

2 回答 2

4

将您的 json 字符串转换为 JsValue,然后在 JsValue 对象上使用 validate。

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)
于 2016-05-01T17:25:17.247 回答
3

类似于@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定义。

于 2016-05-01T17:31:45.160 回答