繁体   English   中英

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

[英]Using scala play-json 2.4.x, how do I extract the name of a json object into a different object?

鉴于此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]

但是文档没有讨论任何有关提取对象名称作为其他地方使用的字段的事情。

编辑:澄清

我的最终状态将是从JSON对象而不是数组解析的JenkinsCredentialsSeq 由于JSON的结构方式。 对于“凭据”下的每个潜在凭据条目,我都将“凭据”:“ UUID”和“凭据”:“ UUID”:“描述”提取到一个对象中

我发现这不使用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)
}

这有效,但不验证位,也不使用转换器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM