akka http - 如何解组查询参数为LocalDate?
问题描述:
我想在像下面阿卡HTTP来解读查询参数:akka http - 如何解组查询参数为LocalDate?
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) =>
我可以解组就一切OK String或诠释,但我想unmarsall的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的解组,但我仍然刚开克同样的错误:
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))
}
}
答
试试这个:
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
}
}
谢谢,这是一个重复的,虽然我没有发现这个问题,当我搜索 – Rory