Search code examples
jsonscalaplayframework-2.1playframework-json

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"
}

Solution

  • 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)
    
      }