【问题标题】:How to parse json with a single field in Playframework2?如何在 Playframework2 中使用单个字段解析 json?
【发布时间】:2014-05-12 17:50:02
【问题描述】:

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

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

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

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

并且我添加了隐式读取方法:

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 解析器的限制吗?

【问题讨论】:

    标签: scala playframework-2.0


    【解决方案1】:

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

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

    // 应该可以隐式val travisUserRepositoriesReads: 读取 [TravisUserRepositories] = ( (JsPath\"repos").read[Seq[TravisReposity]] 映射 (TravisUserRepositories.apply _)

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-13
    • 2018-10-23
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多