Scala Play framework Json 操作

play 框架支持将 jsonclass 自动映射,代码:

package controllers

import javax.inject._
import play.api._
import play.api.libs.json._
import play.api.mvc._

/**
 * This controller creates an `Action` to handle HTTP requests to the
 * application's home page.
 */
@Singleton
class HomeController @Inject()(val controllerComponents: ControllerComponents) extends BaseController {

  case class Person(name: String, age: Int, email: String)
  implicit val personR = Json.reads[Person]
  implicit val personW = Json.writes[Person]
  /**
   * Create an Action to render an HTML page.
   *
   * The configuration in the `routes` file means that this method
   * will be called when the application receives a `GET` request with
   * a path of `/`.
   */
  def index() = Action { implicit request: Request[AnyContent] =>
    val curry = Person("curry", 30, "curry@example.com")
    Ok(Json.obj(
      "code" -> 0,
      "data" -> Json.toJson(curry),
      "msg" -> "ok"
    ))
  }
}

其中这两行:

implicit val personR = Json.reads[Person]
implicit val personW = Json.writes[Person]

定义宏,它会在编译时期自动展开为:Reads[T]Writes[T]。在 Scala 中操作 Json 比使用 Java 要简单许多。