首页 > 解决方案 > 在 Play Framework 中运行时构建读取转换器和案例类

问题描述

我有一个包含以下 JSON 对象数组的文件:

[
    {
      "type": "home",
      "number": 1111
    },
    {
      "type": "office",
      "number": 2222
    },
    {
      "type": "mobile",
      "number": 3333
    }
  ]

在 Play Framework 2.x 中,我将定义一个隐式读取转换器来读取文件并将其转换为 Scala 结构:

implicit val implicitRead : Reads[MyClass] = (
      (JsPath \ "type").read[String] and
      (JsPath \ "number").read[Int]
)  (MyClass.apply _)

Scala案例类定义为:

case class MyClass (myType: String, myNumber: Int)

并解析 JSON:

val json = // file record content    
json.validate[MyClass] match {
  case s: JsSuccess[MyClass] => {
    val myObject: MyClass = s.get
    // do something with myObject
  }
  case e: JsError => {
    // error handling flow
  }

现在,我的问题是我知道 JSON 文件的结构runtime,而不是compilation time。是否可以同时构建隐式读取转换器和案例类runtime

标签: scalaplayframeworkplayframework-2.6play-json

解决方案


case classes直接使用play-json

更改case class为:

case class MyClass (`type`: String, number: Int)

添加json-formatter到伴随对象:

object MyClass {
  implicit val format = Json.format[MyClass]
}

validate函数现在看起来:

val myClass = // file record content    
json.validate[Seq[MyClass]] match {
  case JsSuccess(myClasses, _) => myClasses
  case e: JsError =>  // handle error case
}

这就是你所需要的。如果您对参数名称不满意,可以使用 Wrapper 案例类。


推荐阅读