[json4s]:Extracting Array of different objects

白昼怎懂夜的黑 提交于 2019-12-05 19:05:11

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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!