类型选项[java.sql.Timestamp]不能用作默认值

问题描述 投票:1回答:1

尝试从案例类中获取派生的输入对象。

val UserInputType = deriveInputObjectType[UserRow]()
case class UserRow(id: Int, name: String, lastModifiedTime: Option[java.sql.Timestamp] = None) 

但得到以下错误

Type Option[java.sql.Timestamp] cannot be used as a default value. Please consider defining an implicit instance of `ToInput` for it.

我还定义了时间戳的类型:

  case object DateTimeCoerceViolation extends Violation {
    override def errorMessage: String = "Error during parsing DateTime"
  }

  def parseTime(s: String) = Try(Timestamp.valueOf(s)) match {
    case Success(date) ⇒ Right(date)
    case Failure(_) ⇒ Left(DateTimeCoerceViolation)
  }

  implicit val TimestampType = ScalarType[Timestamp](
    "Timestamp",
    coerceOutput = (ts, _) => ts.getTime,
    coerceInput = {
      case StringValue(ts, _, _, _,_) => parseTime(ts)
      case _ => Left(DateTimeCoerceViolation)
    },
    coerceUserInput = {
      case s: String => parseTime(s)
      case _ => Left(DateTimeCoerceViolation)
    }
  )

怎么解决这个?

scala sangria
1个回答
0
投票

正如错误所说 - 请考虑为它定义ToInput的隐式实例,你必须隐式地为ToInput提供Timestamp。因为没有它,桑格利亚将无法将原始数据序列化到Timestamp

  implicit val toInput = new ToInput[Option[java.sql.Timestamp], Json] {
    override def toInput(value: Option[Timestamp]): (Json, InputUnmarshaller[Json]) = value match {
      case Some(time) => (Json.fromString(time.toString), sangria.marshalling.circe.CirceInputUnmarshaller)
      case None => (Json.Null, sangria.marshalling.circe.CirceInputUnmarshaller)
    }
  }

另一方面,如果使用play-json库,则不必明确定义和使用toInput

例如,在play json中,您可以为TimeStamp定义隐式格式。

implicit val timeStampFormat: Format = ???

以上格式将由桑格利亚Json-Marshaller隐含地用于将Json序列化为Timestamp

© www.soinside.com 2019 - 2024. All rights reserved.