jsonscalanscala-time

Playframework scala reading a json date with RFC1123_PATTERN to nscala DateTime


I am trying to read a date that is in a json object with an specific format of a third party API, for simplicity I will be as as I can. This is the Date

"date_created" -> "Mon, 19 Oct 2015 07:07:03 +0000",

I am trying to parse the json to a custom object like this

(JsPath \ "date_created").read[SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US)].map{ response => new com.github.nscala_time.time.Imports.DateTime(response) } and

Is not working, but is there a way to make this work?

Thank you


Solution

  • You should define a Reads for DateTime

    implicit val readDateTime: Reads[DateTime] = new Reads[DateTime] {
      private val format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US)
    
      override def reads(json: JsValue): JsResult[DateTime] = json match {
    
        case JsString(d) => Try(format.parse(d)).map(t => JsSuccess(new DateTime(t))).getOrElse(error(json))
        case _ => error(json)
      }
    
      private def error(json: JsValue) = JsError(s"Unable to parse $json into a DateTime with format EEE, dd MMM yyyy HH:mm:ss z ")
    }
    

    Then your code would simply be

    (JsPath \ "date_created").read[DateTime]
    

    Note: the code between [] must be a type definition, and in your code example looks like if you were trying to send an instance of a formatter.