简体   繁体   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?

Given this json: 鉴于此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": "_"
}

and this scala destination class: 和这个scala目标类:

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

How can I create a Reads[JenkinsCredentials] to extract that first object name uuid b79a2ba2-lolo-lolo-lolo-lololololol along with the description? 如何创建Reads[JenkinsCredentials]来提取第一个对象名称uuid b79a2ba2-lolo-lolo-lolo-lololololol和说明?

Following the documentation it'd be something along the lines of this: 在遵循文档之后,将遵循以下步骤:

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

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

But the documentation doesn't discuss anything about extracting the names of the objects as a field used somewhere else... 但是文档没有讨论任何有关提取对象名称作为其他地方使用的字段的事情。

EDIT: clarifying 编辑:澄清

My end state would be a Seq of JenkinsCredentials that are parsed from a json Object, not an array. 我的最终状态将是从JSON对象而不是数组解析的JenkinsCredentialsSeq Because of how the JSON is structured. 由于JSON的结构方式。 I'd pull out the "credentials": "UUID" and "credentials":"UUID":"description" into a single object, for each potential credentials entry under "credentials" 对于“凭据”下的每个潜在凭据条目,我都将“凭据”:“ UUID”和“凭据”:“ UUID”:“描述”提取到一个对象中

I figured this out not using the Reads[T] methods: 我发现这不使用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)
}

This works, but doesn't validate bits, and doesn't use a transformer. 这有效,但不验证位,也不使用转换器。

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

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