【问题标题】:Scala Case Class Json Transform With Named Root具有命名根的 Scala 案例类 Json 转换
【发布时间】:2015-09-09 22:37:04
【问题描述】:

我目前正在使用带有 Scala 的 Playframework 2.4 开发一个小型且简单的 Rest API。我确实定义了一个简单的案例类,并且很容易将其转换为 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 scala playframework playframework-2.4


    【解决方案1】:

    您所期望的不是有效的 JSON,即您必须将示例包裹在花括号中以表示对象 - 因为顶级 JSON 元素必须是对象、数组或字符串、数字、布尔值, 或 null 文字。如果您可以接受将结果括在花括号中,即

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

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

    然后创建一个包装案例类应该会为您解决它:

    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]]
    

    【讨论】:

      猜你喜欢
      • 2016-07-27
      • 1970-01-01
      • 2013-04-13
      • 1970-01-01
      • 2011-02-17
      • 1970-01-01
      • 2018-10-19
      • 2014-12-18
      • 1970-01-01
      相关资源
      最近更新 更多