Scala上的Play2:JSON序列化/反序列化

问题描述 投票:0回答:1

我是Play / Scala的新手,并开始将Spring Boot RestAPI移植到Play2作为学习练习。在Java / SpringRest中,只需注释POJO,JSon库即可自动处理序列化/反序列化。

根据我阅读的每个Play2 / Scala教程,我必须为每个模型/案例类编写一个Writer / Reader,如下所示

implicit val writesItem = Writes[ClusterStatus] {
  case ClusterStatus(gpuFreeMemory, gpuTotalMemory, labelsLoaded, status) =>
     Json.obj("gpuFreeMemory" -> gpuFreeMemory,
              "gpuTotalMemory" -> gpuTotalMemory,
              "labelsLoaded" -> labelsLoaded,
              "status" -> status)
}

//HTTP method 
def status() = Action  { request =>
  val status: ClusterStatus = clusterService.status()
  Ok(Json.toJson(status))
}

这意味着如果有一个大的域模型/响应模型,我必须写很多作家/读者来进行序列化/反序列化?

有没有更简单的方法来解决这个问题?

json scala playframework
1个回答
0
投票

您可以尝试“ com.typesafe.play” %%“ play-json”%“ 2.7.2”。要使用它,您只需要执行以下步骤:

1)添加以下依赖项(根据您的项目使用版本):

  "com.typesafe.play" %% "play-json" % "2.7.2",
  "net.liftweb" % "lift-json_2.11" % "2.6.2" 

2)定义格式:

  implicit val formats = DefaultFormats

  implicit val yourCaseClassFormat= Json.format[YourCaseClass]

format定义案例类的读写。

© www.soinside.com 2019 - 2024. All rights reserved.