【问题标题】:Akka-Spray object marshallAkka-Spray 对象编组
【发布时间】:2015-07-26 17:05:55
【问题描述】:

我正在试验 aka 和 spray,我想要实现的是一个简单的对象编组服务。

当我尝试编译代码时,出现以下错误:

Error:(33, 18) could not find implicit value for parameter marshaller:
  spray.httpx.marshalling.Marshaller[ExampleApplication.Password]
  marshal(Password(randomString(8),i,0))
                   ^

代码如下:

import akka.actor.ActorSystem
import spray.http.HttpEntity
import spray.json.DefaultJsonProtocol
import spray.routing.SimpleRoutingApp
import spray.httpx.marshalling._
import spray.json._

object ExampleApplication extends App with SimpleRoutingApp {
  implicit val actorSystem = ActorSystem()
  implicit var i = 0;


  object MyJsonProtocol extends DefaultJsonProtocol {
    implicit val PasswordFormat = jsonFormat3(Password)
  }

  case class Password(pass: String, count: Int, complexity: Int)

  def newPass(cplx: Int):Password = {return Password(randomString(cplx),i,0)}

  startServer(interface = "localhost", port = 8080) {
    get {
      path("passgen") {
        i+=1
        complete {
          marshal(newPass(8))
        }
      }
    }
  }

  def randomString(n: Int): String = {
    n match {
      case 1 => util.Random.nextPrintableChar().toString
      case _ => util.Random.nextPrintableChar.toString ++ randomString(n - 1).toString
    }
  }
}

我还是不明白出了什么问题。

【问题讨论】:

    标签: json scala akka marshalling spray


    【解决方案1】:

    修复它的两个更改:

    import spray.httpx.SprayJsonSupport._
    

    那么即使你在你的应用程序中定义了 JsonProtocol 对象,你仍然必须明确地导入它的成员:

    object MyJsonProtocol extends DefaultJsonProtocol {
      implicit val PasswordFormat = jsonFormat3(Password)
    }
    import MyJsonProtocol._
    

    在这种情况下看起来有点重复,但在大多数用例中,您会在其他地方定义它。

    可选

    无需显式调用marshal即可完成调用:

    complete {
      newPass(8)
    }
    

    【讨论】:

    • 做到了,昨天已经很晚了,在很晚的时候你写了愚蠢的代码,仍然对于httpx导入我很困惑,它不会自动导入
    猜你喜欢
    • 2021-11-22
    • 2019-02-25
    • 1970-01-01
    • 2014-02-21
    • 2014-09-30
    • 2011-10-28
    • 2013-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多