score:19

Accepted answer

it's not necessarily apply or unapply functions you need. it's a) a function that constructs whatever the type you need given some parameters, and b) a function that turns an instance of that type into a tuple of values (usually matching the input parameters.)

the apply and unapply functions you get for free with a scala case class just happen to do this, so it's convenient to use them. but you can always write your own.

normally you could do this with anonymous functions like so:

import java.sql.timestamp
import play.api.libs.functional.syntax._
import play.api.libs.json._

implicit val timestampformat: format[timestamp] = (
  (__ \ "time").format[long]
)((long: long) => new timestamp(long), (ts: timestamp) => (ts.gettime))

however! in this case you fall foul of a limitation with the api that prevents you from writing formats like this, with only one value. this limitation is explained here, as per this answer.

for you, a way that works would be this more complex-looking hack:

import java.sql.timestamp
import play.api.libs.functional.syntax._
import play.api.libs.json._

implicit val rds: reads[timestamp] = (__ \ "time").read[long].map{ long => new timestamp(long) }
implicit val wrs: writes[timestamp] = (__ \ "time").write[long].contramap{ (a: timestamp) => a.gettime }
implicit val fmt: format[timestamp] = format(rds, wrs)

// test it...
val testtime = json.obj("time" -> 123456789)
assert(testtime.as[timestamp] == new timestamp(123456789))

Related Query

More Query from same tag