【问题标题】:Spray client marshalling of custom case class to JSON将自定义案例类的客户端编组喷射到 JSON
【发布时间】:2013-09-11 20:30:34
【问题描述】:

我有以下暗示:

object MyJsonProtocol extends DefaultJsonProtocol {
  implicit val impStartObjSys = jsonFormat3(StartObj.Sys)
  implicit val impStartObjData = jsonFormat6(StartObj.Data)
  implicit val impStartObjStart = jsonFormat3(StartObj.Start)
}

Spray 路由器可以正常工作,我通常可以将对象解组到 StartObj.Start(它将字符串和 sys 和数据作为输入参数)

现在我正在尝试编写负载测试并使用喷雾客户端执行 JSON 请求。不幸的是,它不想接受我的对象作为输入参数,错误:

[错误] Load.scala:85: 找不到类型 >spray.httpx.marshalling.Marshaller[models.StartObj.Start] 的证据参数的隐式值 [错误] 管道(发布(服务器主机,新用户)) [错误] ^

我开始创建一个可以解决此问题的编组器:

  implicit val StartObjMarshaller =
    Marshaller.of[Start](ContentTypes.`application/json`) 
    { (value, contentType, ctx) ⇒ 
       ctx.marshalTo(HttpEntity(contentType, value))
    }

但这里它抱怨 value 不是受支持的类型。它只需要字节数组或字符串。我需要字符串但采用 Json 格式,我应该如何编写这个编组器才能正确解决问题?

谢谢!

【问题讨论】:

    标签: json scala marshalling akka spray


    【解决方案1】:

    好的,我想通了。我需要添加这个导入来支持 json 编组:

    import spray.httpx.SprayJsonSupport._
    

    编组函数之后是:

      implicit def StartObjMarshaller[T](implicit writer: RootJsonWriter[T], 
          printer: JsonPrinter = PrettyPrinter) =
      Marshaller.delegate[T, String](ContentTypes.`application/json`) { value ⇒
        val json = writer.write(value)
        printer(json)
      }
    

    【讨论】:

    • 对。澄清一下:您不再需要使用SprayJsonSupport 编写自己的编组器,因为您引用的定义是从SprayJsonSupport 导入的。
    • 是的,我后来也想通了。像魅力一样工作:) 谢谢。
    猜你喜欢
    • 2017-01-20
    • 2021-02-26
    • 1970-01-01
    • 2020-08-24
    • 1970-01-01
    • 2021-12-11
    • 2016-12-12
    • 1970-01-01
    • 2021-08-20
    相关资源
    最近更新 更多