【问题标题】:spray-json Cannot find JsonWriter or JsonFormat type class for Classspray-json 找不到 Class 的 JsonWriter 或 JsonFormat 类型类
【发布时间】:2016-07-28 06:50:47
【问题描述】:

我仍然遇到同样的错误,我已经定义了编组器(并导入了它);当函数是多态的时,案例类条目似乎不在上下文中。这会引发Cannot find JsonWriter or JsonFormat type class for Case Class。有没有理由为什么 spray-json 找不到案例类的隐式编组器,(即使已定义)这个案例类是否在上下文中?链接到marshaller

import spray.json._
import queue.MedusaJsonProtocol._

object MysqlDb {
 ...
}

case class UserDbEntry(
  id: Int,
  username: String,
  countryId: Int,
  created: LocalDateTime
)

trait MysqlDb {
  implicit lazy val pool = MysqlDb.pool
}

trait HydraMapperT extends MysqlDb {
  val FetchAllSql: String
  def fetchAll(currentDate: String): Future[List[HydraDbRow]]

  def getJson[T](row: T): String
}

object UserHydraDbMapper extends HydraMapperT {
  override val FetchAllSql = "SELECT * FROM user WHERE created >= ?"

  override def fetchAll(currentDate: String): Future[List[UserDbEntry]] = {
    pool.sendPreparedStatement(FetchAllSql, Array(currentDate)).map { queryResult =>
      queryResult.rows match {
        case Some(rows) =>
          rows.toList map (x => rowToModel(x))
        case None => List()
      }
    }
  }

  override def getJson[UserDbEntry](row: UserDbEntry): String = {
      HydraQueueMessage(
        tableType = HydraTableName.UserTable,
        payload = row.toJson.toString()
      ).toJson.toString()
  }

  private def rowToModel(row: RowData): UserDbEntry = {
    UserDbEntry (
      id        = row("id").asInstanceOf[Int],
      username  = row("username").asInstanceOf[String],
      countryId = row("country_id").asInstanceOf[Int],
      created   = row("created").asInstanceOf[LocalDateTime]
    )
  }
}

payload = row.toJson.toString() 找不到 UserDbEntry 的编组器

【问题讨论】:

    标签: scala spray-json


    【解决方案1】:

    您已在本地定义 UserDbEntry,并且该类型没有 JSON 编组器。添加以下内容:

     implicit val userDbEntryFormat = Json.format[UserDbEntry]
    

    鉴于UserDbEntry 是本地案例类,我不确定您如何调用row.toJson。那里一定有一个宏,但很明显它不在本地UserDbEntry的范围内。

    编辑

    现在我看到your Gist,看起来你有包依赖问题。按照设计,它将是圆形的。您已经在 package com.at.medusa.core.queue 中定义了 JSON 编组器,它导入了 UserDbEntry,它依赖于 package com.at.medusa.core.queue 进行编组。

    【讨论】:

    • 不,我在别处定义了隐式编组器;我只是不明白为什么会这样。我已经编辑了这个部分,你可以看到我 import queue.MedusaJsonProtocol._ DateTimeFormat 不能用 spray-json 编组,你必须定义一个自定义编组器。
    • 无论您在哪里定义它们,它们都不在范围内。你必须包括它。也许为这两个文件添加一个要点。
    猜你喜欢
    • 2018-09-19
    • 2015-03-18
    • 2016-09-22
    • 1970-01-01
    • 1970-01-01
    • 2020-07-30
    • 2012-12-12
    • 1970-01-01
    • 2012-08-23
    相关资源
    最近更新 更多