使用SprayJson

时间:2017-01-06 15:35:54

标签: scala marshalling

我是Scala和Akka的新手。

我有以下案例类:

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

我必须以Json格式发送List [Demo]作为对get请求的响应,但由于Date,我在以下代码中遇到问题:

隐式val演示格式:RootJsonFormat [演示] = jsonFormat3(演示)

如果你能帮助我,我将不胜感激

1 个答案:

答案 0 :(得分:1)

您需要提供java.util.Date的格式,因为默认情况下,喷雾没有。

快速谷歌搜索会导致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.SSSZ")
  }

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

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

在您编写implicit val demoFormat: RootJsonFormat[Demo] = jsonFormat3(Demo)的片段代码中导入DateMarshalling._,现在应该没问题了:)