【问题标题】:How to specify a request parameter as Json type如何将请求参数指定为 Json 类型
【发布时间】:2017-07-28 12:01:15
【问题描述】:

我正在创建一个需要 Json 的 Finch 端点。

URL - LogBundles/Long JSON 消息/进程

我正在使用 json4s 库进行 Json 解析

如何将 body 指定为 json 类型或者如何在 LogBundles 和 Process 之间传递 Json 值?

我不能做 body.as[case class] 因为我不知道 Json 的确切结构。 我会在解析时只寻找一个特定的键。

代码

val bundleProcessEndpoint: Endpoint[String] = put("LogBundles" :: body :: "Process" ) { id =>
                 val jsonBody = parse(id)}

错误

找不到参数 d 的隐含值:io.finch.Decode.Aux[A,CT] [错误] val bundleProcessEndpoint: Endpoint[String] = put("LogBundles" :: body :: "Process" ) { id:JsonInput =>

【问题讨论】:

    标签: scala finagle finch twitter-finagle


    【解决方案1】:

    有几种方法可以做到这一点,尽管它们都不被 Finch 认为是惯用的。在Endpoint 中接受任意 JSON 对象的或多或少安全的方法是下拉到通过您正在使用的 JSON 库公开的 JSON AST API。对于 json4s,它将是 org.json4s.JsonAST.JValue

    scala> import io.finch._, io.finch.json4s._, org.json4s._
    
    scala> implicit val formats: Formats = DefaultFormats
    formats: org.json4s.Formats = org.json4s.DefaultFormats$@5ee387bc
    
    scala> val e = jsonBody[JsonAST.JValue]
    e: io.finch.Endpoint[org.json4s.JsonAST.JValue] = body
    
    scala> e(Input.post("/").withBody[Application.Json](Map("foo" -> 1, "bar" -> "baz"))).awaitValueUnsafe()
    res2: Option[org.json4s.JsonAST.JValue] = Some(JObject(List((foo,JInt(1)), (bar,JString(baz)))))
    

    这将为您提供一个需要手动操作的 JsonAST.JValue 实例(我假设为此公开了一个模式匹配 API)。

    另一种(也是更危险的)解决方案是让 Finch/JSON4S 将 JSON 对象解码为Map[String, Any]。但是,这仅在您不希望客户端将 JSON 数组作为顶级实体发送时才有效。

    scala> import io.finch._, io.finch.json4s._, org.json4s._
    
    scala> implicit val formats: Formats = DefaultFormats
    formats: org.json4s.Formats = org.json4s.DefaultFormats$@5ee387bc
    
    scala> val b = jsonBody[Map[String, Any]]
    b: io.finch.Endpoint[Map[String,Any]] = body
    
    scala> b(Input.post("/").withBody[Application.Json](Map("foo" -> 1, "bar" -> "baz"))).awaitValueUnsafe()
    res1: Option[Map[String,Any]] = Some(Map(foo -> 1, bar -> baz))
    

    【讨论】:

    • 你好弗拉基米尔,如果我错了,请纠正我。但我的问题是如何使用来自端点的 Json 有效负载来处理用户发送的 PUT 请求。 WithBody 覆盖用户发送的 Payload。
    • 这两个示例中的最后几行只是为了演示端点在给定输入上返回的内容。您的应用程序中不需要它。我鼓励你看看我们的user guide,它应该可以帮助你消除所有的困惑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 2013-12-07
    • 2012-05-13
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多