使用scala play-json 2.4.x,如何将json对象的名称提取到另一个对象中?

时间:2015-09-11 16:07:08

标签: json scala playframework-2.0

鉴于此json:

{
  "credentials": {
    "b79a2ba2-lolo-lolo-lolo-lololololol": {
      "description": "meaningful description",
      "displayName": "git (meaningful description)",
      "fullName": "credential-store/_/b79a2ba2-lolo-lolo-lolo-lololololol",
      "typeName": "SSH Username with private key"
    }
  },
  "description": "Credentials that should be available irrespective of domain specification to requirements matching.",
  "displayName": "Global credentials (unrestricted)",
  "fullDisplayName": "Credentials » Global credentials (unrestricted)",
  "fullName": "credential-store/_",
  "global": true,
  "urlName": "_"
}

和这个scala目标类:

case class JenkinsCredentials(uuid: String, description: String)

如何创建Reads[JenkinsCredentials]以提取第一个对象名称uuid b79a2ba2-lolo-lolo-lolo-lololololol以及说明?

遵循文档,它就是这样的:

implicit val credsReader: Reads[JenkinsCredentials] = (
  (JsPath).read[String] and
    (JsPath \ "description").read[String]
  )(JenkinsCredentials.apply _)

(Json.parse(content) \\ "credentials").validate[Seq[JenkinsCredentials]

一起使用

但是文档并没有讨论如何将对象的名称提取为在其他地方使用的字段...

编辑:澄清

我的结束状态是Seq JenkinsCredentials,它是从json对象解析而不是数组。因为JSON的结构如何。我将取出"凭证":" UUID"和"凭证":" UUID":"描述"在"凭证"

下的每个潜在凭证条目的单个对象

1 个答案:

答案 0 :(得分:0)

我认为这不是使用Reads[T]方法:

//Get the key names inside of the credentials
(json \ "credentials").as[JsObject].fields.map{ case (credId, value) =>
    JenkinsCredentials(credId, (value \ "description").validate[String].get)
}

这有效,但不验证位,也不使用变压器。