Scala Case Class Json 使用命名根进行转换

Scala Case Class Json Transform With Named Root

我目前正在使用 Playframework 2.4 和 Scala 开发一个小而简单的 Rest API。我确实定义了一个简单的案例 class 并且这很容易转换为 Json。现在我想让对象(如果结果是一个列表,这个列表中的每个条目)命名。

这可以简单地实现吗?我刚刚找到 this,但它并没有真正解决我的问题。

case class Employee(name: String, address: String, dob: Date, joiningDate: Date, designation: String)

// Generates Writes and Reads for Feed and User thanks to Json Macros
implicit val employeeReads = Json.reads[Employee]
implicit val employeeWrites = Json.writes[Employee]

所以,现在我得到

{
  "name": "a name",
  "address": "an address",
  ...
}

但我想看到类似的内容:

"employee": {
  "name": "a name",
  "address": "an address",
  ...
}

对于对象列表,应该应用相同的规则:

"employees": [
  "employee": {
    "name": "a name",
    "address": "an address",
    ...
  },
  ...
]

这可能使用给定的写入宏吗?我现在有点迷路了;-(

您期望的内容无效 JSON,即您必须将示例用大括号括起来以表示一个对象 - 因为顶级 JSON 元素必须是一个对象,数组,或字符串、数字、布尔值或 null 文字。如果用大括号括起来的结果对你来说是可以接受的,即

{
  "employee": {
    "name": "a name",
    "address": "an address",
    ...
  }
}

{
  "employees": [
    {
      "employee": {
        "name": "a name",
        "address": "an address",
        ...
      }
    },
    ...
  ]
}

然后创建一个包装器 class 应该可以为您解决:

import play.api.libs.json._
import play.api.libs.functional.syntax._

// instead of using `reads` and `writes` separately, you can use `format`, which covers both
implicit val employeeFormat = Json.format[Employee]
case class EmployeeWrapper(employee: Employee)

implicit val employeeWrapperFormat = Json.format[EmployeeWrapper]
implicit val employeesWrapperFormat =
  (__ \ "employees").format[List[EmployeeWrapper]]