Corne Elshof Corne Elshof - 4 months ago 13x
JSON Question

Add field to existing JSON object with sprayJSON (scala)

I made a case class to store some of my data. The case class looks like the following:

case class Job(id: Option[Int], title: String, description: Option[String],
start: Date, end: Option[Date], customerId: Int)

I was using the following formatter to write/read my JSON objects:

implicit val jobFormat = jsonFormat6(Job.apply)

I've got some problems with the write/read because I need to add a field to the JSON (but not to the case class), for example: "test": "test". I tried to write a custom read/write with the following code:

implicit object jobFormat extends RootJsonFormat[Job] {
override def read(json: JsValue): JobRow = ???

override def write(job: Job): JsValue = ??

I couldn't get the working code, could somebody help me with this problem?

Thanks in advance!


What jsonFormat6 does is to create you autogenerated RootJsonFormat[Job] object. You can create your custom instances with extending RootJsonFormat[Job]. In this case, you need to create custom instance that decorates autogenerated one and adds logic on write method.

The code will look like this:

implicit object JobFormat extends RootJsonFormat[Job] {
  // to use autogenerated jobFormat
  val jobFormat = jsonFormat6(Job.apply)

  // leave read at it is
  override def read(json: JsValue): JobRow =

  // Change write to add your custom logic
  override def write(job: Job): JsValue = {
    val json = jobFormat.write(job).asJsonObject
    JsObject(json.fields + ("test" -> JsString("test")))

PS: I haven't compiled code, however, overall implementation will look like this.