簡體   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