'Marshalling java.util.Date with SprayJson

I am new to Scala and Akka.

I have the following case class:

case class Demo(userId: String, date: java.util.Date, message: String) extends     BusinessModel

I have to send List[Demo] in Json format as response to a get request but I am facing problem in the following code due to Date:

implicit val demoFormat: RootJsonFormat[Demo] = jsonFormat3(Demo)

I would be grateful if you may kindly help me out



Solution 1:[1]

You need to provide a format for java.util.Date, since spray doesn't have one by default.

A quick google search leads to https://gist.github.com/owainlewis/ba6e6ed3eb64fd5d83e7 :

import java.text._
import java.util._
import scala.util.Try
import spray.json._

object DateMarshalling {
  implicit object DateFormat extends JsonFormat[Date] {
    def write(date: Date) = JsString(dateToIsoString(date))
    def read(json: JsValue) = json match {
      case JsString(rawDate) =>
        parseIsoDateString(rawDate)
          .fold(deserializationError(s"Expected ISO Date format, got $rawDate"))(identity)
      case error => deserializationError(s"Expected JsString, got $error")
    }
  }

  private val localIsoDateFormatter = new ThreadLocal[SimpleDateFormat] {
    override def initialValue() = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX")
  }

  private def dateToIsoString(date: Date) =
    localIsoDateFormatter.get().format(date)

  private def parseIsoDateString(date: String): Option[Date] =
    Try{ localIsoDateFormatter.get().parse(date) }.toOption
}

Import DateMarshalling._ in piece code where you have wrote implicit val demoFormat: RootJsonFormat[Demo] = jsonFormat3(Demo) and it should be ok now :)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1