I'm using play.api.libs.json._ library. I have this kind of Scala class. I need to read / write this class in Json format. As there is no implicit reader/ writer for Timestamp. I have to provide my own. I tried couple ways unfortunately none of them worked. Could you please suggest me how it is done? Thanks in advance!
case class Event(id: Long, startTime: Option[java.sql.Timestamp] = None, endTime: Option[java.sql.Timestamp] = None)
I would like to POST / GET in following Json format
{
"id": 1,
"startTime": "2011-10-02 18:48:05.123456",
"endTime": "2011-10-02 20:48:05.123456"
}
just add before Json Reader or Json Format for Event class
import play.api.libs.json.Json._
import play.api.libs.json._
def timestampToDateTime(t: Timestamp): DateTime = new DateTime(t.getTime)
def dateTimeToTimestamp(dt: DateTime): Timestamp = new Timestamp(dt.getMillis)
implicit val timestampFormat = new Format[Timestamp] {
def writes(t: Timestamp): JsValue = toJson(timestampToDateTime(t))
def reads(json: JsValue): JsResult[Timestamp] = fromJson[DateTime](json).map(dateTimeToTimestamp)
}
What I did code for a personal project:
implicit object timestampFormat extends Format[Timestamp] {
val format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS'Z'")
def reads(json: JsValue) = {
val str = json.as[String]
JsSuccess(new Timestamp(format.parse(str).getTime))
}
def writes(ts: Timestamp) = JsString(format.format(ts))
}
And don't forget to import this:
import java.sql.Timestamp
import java.text.SimpleDateFormat
import play.api.Play.current
import play.api.libs.json._
It respects Javascript dates standard.
Source: https://github.com/BinaryBrain/Gamers/blob/master/server/play/app/models/Package.scala
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With