[json4s]:提取不同对象的数组 [英] [json4s]:Extracting Array of different objects

查看:179
本文介绍了[json4s]:提取不同对象的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用facebook graph API,响应看起来与此类似:

I am using the facebook graph API and the responses look similar to this:

{
  "data": [
    {
      "id": "311620272349920_311718615673419", 
      "from": {
        "id": "1456046457993048", 
        "name": "Richard Ettinson"
      }, 
      "to": {
        "data": [
          {
            "id": "311620272349920", 
            "name": "Barbara Fallerman"
          }
        ]
      }, 
      "with_tags": {
        "data": [
          {
            "id": "311620272349920", 
            "name": "Barbara Fallerman"
          }
        ]
      }, 
      "message": "I was gong out with her", 
      "actions": [
        {
          "name": "Comment", 
          "link": "https://www.facebook.com/311620272349920/posts/311718615673419"
        }, 
        {
          "name": "Like", 
          "link": "https://www.facebook.com/311620272349920/posts/311718615673419"
        }
      ]
}

例如,我设法通过

val extracted = (json \ "data" \"from").extract[PostFrom]

但是我担心如果使用此技术,我将需要多次传递Json来提取所需的所有值,这可能会导致性能下降.

But I worry that if I use this technique I will need to pass over the Json multiple times to extract all the values I need which could lead to a bad performance.

我如何才能从非相似对象数组中将这些字段提取到case类中?

How exactly could I extract these fields into case classes from the array of non similar objects?

我尝试使用以下case classes:

abstract class BaseResponse()
case class Data(list:List[Post])
case class Post(id: String, post: PostFrom) extends BaseResponse
case class PostFrom(id: String, name:String)

哪个总是导致一个空的列表,有没有办法找回Data类,其中包含我感兴趣的某些类的列表? (例如,顶级idfromwith_tags)

Which always lead to an empty List, is there a way to get back a Data class which has a list of certain classes which I am interested in? (As example the top level id, from and with_tags)

推荐答案

我发现一种可能性是使用更多的case类而不是继承:

A possibility I found was to use more case classes instead of inheritance:

case class Root[T](data:Option[T])
case class Post(id: String, from: From, message: String)
case class From(id: String, name:String)

基本上,必须有一个采用某种图形响应对象的根对象,此外它是可选的,这样,如果响应解析出现问题,它就不会抛出异常.

Basically there has to be a root object which takes some kind of graphs response object, additionally it is optional so that it won't throw an exception if there was a problem with the parsing of the response.

然后我通过以下方式使用它:

I then used it in the following way:

val body = r.entity.asString
val json = parse(r.entity.asString)
val root = json.extract[Root[Post]]

root.data match {
  case Some(post) =>
      val tagger = Tagger(post.from.id, post.from.name, post.id, post.message)
      log.info(s"We received $tagger")
      originalSender ! RetrievedTagger(tagger)

  case None => originalSender ! NoTaggerFound
}

这篇关于[json4s]:提取不同对象的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆