akka http - 如何将查询参数解组为LocalDate?

时间:2017-10-09 09:24:56

标签: scala spray akka-http

我想在akka http中解组一个查询参数,如下所示:

name=jim&age=30&dob=11-20-1990

import java.time.LocalDate
import akka.http.scaladsl.marshalling.ToResponseMarshallable
import akka.http.scaladsl.server._
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.model.headers.RawHeader
import akka.http.scaladsl.server.Directives.{complete, _}
...
parameters(('name.as[String].?, 'age.as[Int].?, 'dob.as[String].?)) { (name, age, dob) =>

我可以将所有内容解组为String或Int,但是我想将dob解组为java.util.LocalDate,如下所示:

parameters(('name.as[String].?, 'age.as[Int].?, 'dob.as[LocalDate].?)) { (name, age, dob) =>

但是,我收到以下错误:

[error] routes/Router.scala:141: type mismatch;
[error]  found   : (akka.http.scaladsl.common.NameOptionReceptacle[Int], akka.http.scaladsl.common.NameOptionReceptacle[Int], akka.http.scaladsl.common.NameOptionReceptacle[java.time.LocalDate])
[error]  required: akka.http.scaladsl.server.directives.ParameterDirectives.ParamMagnet
[error]             parameters(('$top.as[Int].?, '$skip.as[Int].?, 'modified_date.as[LocalDate].?)) { (top, skip, modifiedDate) =>

我尝试在范围内添加自定义LocalDate unmarshaller,但我仍然遇到同样的错误:

implicit val LocalDateUnmarshaller = new JsonReader[LocalDate] {

      def read(value: JsValue) = value match {
        case JsString(x) => LocalDate.parse(x)
        case x => throw new RuntimeException(s"Unexpected type %s on parsing of LocalDate type".format(x.getClass.getName))
      }
    }

1 个答案:

答案 0 :(得分:0)

试试这个:

object LocalDateUnmarshaller {

  implicit val booleanFromStringUnmarshaller: Unmarshaller[String, LocalDate] =
    Unmarshaller.strict[String, LocalDate] { string ⇒
      import java.time.LocalDate
      import java.time.format.DateTimeFormatter
      var formatter = DateTimeFormatter.ofPattern("yyyy-MMM-dd")
      val date = LocalDate.parse(string, formatter)
      date
    }

}
相关问题