1

I am currently working on a small and easy Rest API using the Playframework 2.4 with Scala. I did define a simple case class and this gets transformed into Json rather easy. Now I would like to have the object (and if the result is an list, each entry in this list) named.

Is this possible in an easy manner? I just found this, but it does not really solve my issue.

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]

So, right now I do get

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

But I would like to see something like:

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

For a list of objects the same rule should apply:

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

This possible using the given Writes Macros? I am slightly lost right now ;-(

Community
  • 1
  • 1
triplem
  • 1,324
  • 13
  • 26

1 Answers1

1

What you expect is not valid JSON, i.e. you would have to have your examples wrapped in curly braces to denote an object - because the top-level JSON element must be an object, an array, or a string, number, boolean, or null literal. If having the result wrapped in curly braces is acceptable for you, i.e.

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

and

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

then creating a wrapper case class should solve it for you:

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]]
Zoltán
  • 21,321
  • 14
  • 93
  • 134