Reputation: 199
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!
Upvotes: 2
Views: 4316
Reputation: 1019
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 =
jobFormat.read(json)
// 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.
Upvotes: 7