如何使用 Dispatch 解析 JSON 请求?
我正在学习 Scala,并试图了解特征是如何工作的(特别是与 Dispatch 库一起使用)。
我有这样的事情:
import dispatch._
import dispatch.liftjson._
object Foo
{
def main(cmd: Array[String])
{
val http = new Http;
val req = :/("example.com") / path ># (list ! obj);
val res = http(req);
}
}
不幸的是,它抱怨 ># 没有在dispatch.Request 中注册。该特征在dispatch.liftjson中进行了描述,我的假设是我只需要导入该特征(_应该覆盖)即可注册。
I'm learning Scala, and attempting to understand how traits are working (specifically with the Dispatch library).
I've got something like this:
import dispatch._
import dispatch.liftjson._
object Foo
{
def main(cmd: Array[String])
{
val http = new Http;
val req = :/("example.com") / path ># (list ! obj);
val res = http(req);
}
}
Unfortunately, it's complaining that ># is not registered with dispatch.Request. The trait is described within dispatch.liftjson, and it was my assumption that I should just need to import that trait (which _ should cover) for it to register.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该从
dispatch.liftjson.Js._
导入。拥有某种特质并没有什么帮助,因为你并没有使用它。
JS._
导入会将JS
对象的所有内容引入您的范围,包括 隐式转换requestToJsonVerbs
,它来自trait ImplicitJsonVerbs
。此方法将您从:/("example.com") / path
获得的标准 DispatchRequest
转换为JsonVerbs
,其中有方法>#
。下面是我如何查询 API 的简短示例:
如您所见,我有正确的导入(加上一些 Lift< /a> 我喜欢的库),然后我的
Request
'有'一个>#
方法。我给>#
一个与预期签名 ((JValue) ⇒ T
) 匹配的函数,然后我们就可以开始了。如果您想知道,我专门使用 lift-json 提取案例类的功能,这意味着
T
将是Device
。但是,如果 lift-json 无法将JValue
转换为Device
,它也会引发异常,因此我用Helper.tryo 包装了整个请求
,一个 Lift 辅助方法,它包装了一个 try-catch 调用,返回一个Box
。Box
类似于标准 ScalaOption
,但添加了Failure
,它指示为什么Box
为空。因此,在这种情况下,我将得到Full[Device]
或Failure
。便利!You should be importing from
dispatch.liftjson.Js._
.Having a trait isn't helpful, as you're not then using it. The
JS._
import will bring all the contents of theJS
object into your scope, including the implicit conversionrequestToJsonVerbs
which it has fromtrait ImplicitJsonVerbs
. This method converts a standard DispatchRequest
, which you have from:/("example.com") / path
, to aJsonVerbs
, which has the method>#
.Here's an abridged sample of how I query an API:
As you can see, I have the correct imports (plus some for some Lift libraries I like), and my
Request
then 'has' a>#
method. I give>#
a function that matches the expected signature ((JValue) ⇒ T
) and away we go.In case you're wondering, I'm specifically using lift-json's ability to extract to case classes, meaning that
T
will beDevice
. However, lift-json also throws an exception if it is unable to convert theJValue
to aDevice
, so I've wrapped my whole request withHelper.tryo
, a Lift helper method that wraps a try-catch call, returning aBox
.Box
is like the standard ScalaOption
but with the addition ofFailure
, which indicates why aBox
is empty. So, in this case I will get either aFull[Device]
or aFailure
. Handy!