【问题标题】:implicit reads in controller class for PUT function SCALA play framework在控制器类中隐式读取 PUT 函数 SCALA 播放框架
【发布时间】:2023-04-10 02:39:02
【问题描述】:

尝试从客户端读取 JSON 数据并对其进行解析,因此我可以使用 insert 方法将其插入到表中,但我对 Play 2.5 和 Slick 3.1.1 的隐式读取会引发 Option[BigDecimal] 错误,为什么?

object RBooks {implicit val xReads: Reads[xRow] = (
  (JsPath \ "bookId").read[Option[BigDecimal]] and
  (JsPath \ "bookName").read[Option[String]] and
  (JsPath \ "bookDesc").read[Option[String]] and
  (JsPath \ "enabled").read[Option[Char]] and
  (JsPath \ "primaryBook").read[Option[Char]] and
  (JsPath \ "bookType").read[Option[String]] and
  (JsPath \ "bookCurrency").read[Option[String]] and
  (JsPath \ "startDate").read[Option[java.sql.Timestamp]] and
  (JsPath \ "endDate").read[Option[java.sql.Timestamp]] and
  (JsPath \ "allocationsEnabled").read[Option[Char]] and
  (JsPath \ "arrPrefix").read[Option[String]] and
  (JsPath \ "creationDate").read[Option[java.sql.Timestamp]] and    
  (JsPath \ "createdBy").read[Option[String]] and
  (JsPath \ "lastUpdateDate").read[Option[Timestamp]] and
  (JsPath \ "lastUpdatedBy").read[Option[String]]
)(slickLib.xRow.apply  _)

我得到的错误输出:

No Json deserializer found for type Option[BigDecimal]. Try to implement an implicit Reads or Format for this type.(xRow.apply  _) this code is throwing a error: (JsPath \ "bookId").read[Option[BigDecimal]] and 

Play Scala 中的.read 不支持 Option[BigDecimal] 吗?

【问题讨论】:

  • 你为什么要Option[BigDecimal]而不是Option[Decimal]
  • 是的,我需要使用 Option[BigDecimal],slickLib.xRow.apply _) 没有它会变红,如果我运行代码,我会得到错误,我不明白为什么 scala 不是接受这个隐式读取。

标签: json scala slick-3.0 playframework-2.5


【解决方案1】:

不要使用read[Option[Anytype]]。请改用readNullable[Anytype]。 示例:

 (JsPath \ "bookId").readNullable[BigDecimal]

对于不支持的类型,您应该编写自己的解析器或从支持的类型转换为您想要的类型。例如你可以这样处理java.sql.Timestamp

import java.sql.Timestamp
(__ \ 'creationDate).readNullable[Long].map(_.map(new Timestamp(_)))

【讨论】:

    【解决方案2】:

    Play 2.5 scala 12.11.x 不支持 Option[BigDecimal]。另一种方法是使用 json4s 之类的库来处理带有 slick 的 ORM 项目。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多