[json4s]:提取不同对象的数组

编程入门 行业动态 更新时间:2024-10-17 07:36:03
本文介绍了[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": "www.facebook/311620272349920/posts/311718615673419" }, { "name": "Like", "link": "www.facebook/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类,其中包含我感兴趣的某些类的列表? (例如,顶级id,from和with_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]:提取不同对象的数组

本文发布于:2023-07-14 14:45:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1105096.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   对象   json4s

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!