Scala JsObject到嵌套类

时间:2014-04-24 17:50:44

标签: scala playframework-2.0

我有这个场景即时获取Facebook feed(facebook api)列表到json对象列表。 比我想要反序列化到类对象列表。

第一个问题是,哪种数据结构将是最佳做法? (cass class,tratis or regular class)

我就是这样做的,我在帖子案例类中创建了评论列表

case class Post(id: String, fromId: String, fromName: String, message: String, fullUrl:     String, createdTime: String, updateTime: String ,List[Comment]) {   
 }
  case class Comment(id: String, fromId: String, fromName: String, message: String, creationTime: String, likeCount: Int)

然后我就像那样映射

 implicit val post = (
(__ \ "id").read[String] and
  (__ \ "from").\("id").read[String] and
  (__ \ "from").\("name").read[String]  and
  (__ \ "message").read[String]  and
  (__ \ "actions").\\("link").read[String]  and
  (__ \ "created_time").read[String]  and
  (__ \ "updated_time").read[String]
  )(Post)

第二个问题是如何映射列表?

感谢,

miki

1 个答案:

答案 0 :(得分:1)

  1. 在这种情况下,案例类看起来很不错。
  2. 您需要为评论定义相同的隐式阅读器,然后将读者更改为类似的帖子:

    implicit val post = 2
    (__ \ "id").read[String] and
      (__ \ "from").\("id").read[String] and
      (__ \ "from").\("name").read[String]  and
      (__ \ "message").read[String]  and
      (__ \ "actions").\\("link").read[String]  and
      (__ \ "created_time").read[String]  and
      (__ \ "updated_time").read[String] and
      (__ \ "comments").reads[List[Comment]]
    )(Post)