Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala playframework implicit reader writer for Timestamp

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"
}
like image 328
masiboo Avatar asked Mar 02 '15 14:03

masiboo


2 Answers

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)

  }
like image 67
Lucky Libora Avatar answered Oct 23 '22 15:10

Lucky Libora


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

like image 41
Binary Brain Avatar answered Oct 23 '22 15:10

Binary Brain