如何用Playframework2中的单个字段解析json?

时间:2014-05-12 09:41:37

标签: scala playframework-2.0

我正在尝试解析具有以下结构的Travis-ci api response

{
    repos: [
          {"id": ..., "slug": ...}, 
          {"id": ..., "slug": ...}, 
          {"id": ..., "slug": ...}
    ]
}

所以我决定创建反映json结构的case类:

case class TravisRepository(id: String, slug: String)
case class TravisUserRepositories(repos: Seq[TravisRepository])

我添加了隐式Read方法:

implicit val travisRepositoryReads: Reads[TravisRepository] = (
    (JsPath \ "id").read[String] and
    (JsPath \ "slug").read[String]
)(TravisRepository.apply _)

implicit val travisUserRepositoriesReads: Reads[TravisUserRepositories] = (
    (JsPath \ "repos").read[Seq[TravisReposity]]
)(TravisUserRepositories.apply _)

但是,第二次读取未编译时出现以下错误:

Overloaded method value [read] cannot be applied to (Seq[utils.TravisRepository] => utils.TravisUserRepositories)

在第二次读取时添加另一列时,将进行编译。使用单列,这不再编译。有人可以解释为什么这不编译?它是Play-Json解析器的限制吗?

1 个答案:

答案 0 :(得分:2)

这只是因为你的案例“你的案例类中只有一个字段”...... 为了能够使用功能组合,您至少需要2个字段。

  

//可以隐式val travisUserRepositoriesReads:   读[TravisUserRepositories] =(       (JsPath \“repos”)。读[Seq [TravisReposity]]和       ...)(TravisUserRepositories.apply _)

     

//应该是OK隐式val travisUserRepositoriesReads:   读[TravisUserRepositories] =(       (JsPath \“repos”)。阅读[Seq [TravisReposity]]地图(TravisUserRepositories.apply _)