【问题标题】:akka http - how to unmarshall query param as LocalDate? [duplicate]akka http - 如何将查询参数解组为 LocalDate? [复制]
【发布时间】:2017-10-09 09:24:56
【问题描述】:

我想在 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 解组器,但我仍然收到相同的错误:

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))
      }
    }

【问题讨论】:

  • 谢谢,这是重复的,虽然我在搜索时没有找到那个问题

标签: scala spray akka-http


【解决方案1】:

试试这个:

object LocalDateUnmarshaller {
  
  import java.time.LocalDate
  import java.time.format.DateTimeFormatter

  implicit val localDateFromStringUnmarshaller: Unmarshaller[String, LocalDate] =
    Unmarshaller.strict[String, LocalDate] { string =>
      val formatter = DateTimeFormatter.ofPattern("yyyy-MMM-dd")
      val date = LocalDate.parse(string, formatter)
      date
    }
  
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-07
    • 1970-01-01
    • 2019-03-13
    • 2016-03-23
    • 1970-01-01
    • 1970-01-01
    • 2015-08-30
    • 2016-02-08
    相关资源
    最近更新 更多