如何从dispatch.json.JsObject中提取

5 twitter json scala lift scala-dispatch

我需要做些什么才能为friends_count提取值.我注意到screen_name已经在Status对象和case类中定义.仍然需要扩展Js或JsObject的不同

object TweetDetails extends Js { val friends_count = 'friends_count ? num }
Run Code Online (Sandbox Code Playgroud)

然后将它与JsObjects列表中的每个json对象进行模式匹配,如下所示.符号令人困惑:

scala> val friends_count = 'friends_count ! num  // I wish SO understood Scala's symbols
val twtJsonList = http(Status("username").timeline)
twtJsonList foreach {
      js =>
        val Status.user.screen_name(screen_name) = js
        val Status.text(text) = js
        val friends_counts(friends_count) = js //i cannot figure out how to extract this
        println(friends_count)
        println(screen_name)
        println(text)
Run Code Online (Sandbox Code Playgroud)

}

Aar*_*ron 6

通常,Scala符号可以被认为是唯一的标识符,它始终是相同的.每个符号相同的符号指的是完全相同的内存空间.从Scala的角度来看,没有什么比他们更特别了.

然而,Dispatch-Json将符号变成了符号,使它们成为JSON属性提取器.要查看负责pimping的代码,请查看SymOp类和JsonExtractor.scala代码的其余部分.

让我们编写一些代码来解决您正在查看的问题,然后分析发生了什么:

trait ExtUserProps extends UserProps with Js {
  val friends_count = 'friends_count ! num 
}
object ExtUser extends ExtUserProps with Js

val good_stuff = for {
  item <- http(Status("username").timeline)
  msg = Status.text(item)
  user = Status.user(item)
  screen_name = ExtUser.screen_name(user)
  friend_count = ExtUser.friends_count(user)
} yield (screen_name, msg, friend_count)
Run Code Online (Sandbox Code Playgroud)

我们要做的第一件事是在Dispatch-Twitter模块中扩展UserProps特性,为它提供一个friends_count提取器,然后定义一个ExtUser可以用来访问该提取器的对象.因为ExtUserProps扩展了UserProps,它也扩展了Js,我们得到sym_add_operators范围内的方法,将我们的符号'friends_count转换为SymOp案例类.然后我们!在SymOp上调用该方法,然后我们将Extractor传递num给它,它创建一个Extractor,在JSON对象上查找属性"friends_count",然后在返回之前将其解析为数字.对于这么少的代码,有一点点.

The next part of the program is just a for-comprehension that calls out to the Twitter timeline for a user and parses it into JsObjects which represent each status item, them we apply the Status.text extractor to pull out the status message. Then we do the same to pull out the user. We then pull the screen_name and friend_count out of the user JsObject and finally we yield a Tuple3 back with all of the properties we were looking for. We're then left with a List[Tuple3[String,String,BigDecimal]] which you could then iterate on to print out or do whatever with.

我希望清除一些东西.Dispatch库非常具有表现力,但是它可能有点难以理解,因为它使用了许多Scala技巧,有些人只是学习Scala不会马上得到它.但是继续插入和玩游戏,以及查看测试和源代码,你会看到如何使用Scala创建强大的DSL.