我正在編寫一些RESTful API測試案例,並且沒有與scala playframwork一起工作的經驗。如何在scala中解析json列表或數組以用於播放框架2.2
這是我的JSON的一個例子。
[ {
"size" : "5082",
"date-created" : "Wed Nov 19 17:10:39 CST 2014",
"id" : "546d236fb84e894eefd8f769",
"content-type" : "image/png",
"filename" : "chrome-on-windows.PNG"
}, {
"size" : "15684",
"date-created" : "Mon Jan 12 17:28:02 CST 2015",
"id" : "54b4588266b3d11b1c1e9db6",
"content-type" : "image/png",
"filename" : "logos_ncsa.png"
}, {
"size" : "1267871",
"date-created" : "Mon Jan 12 17:28:03 CST 2015",
"id" : "54b4588366b3d11b1c1e9dba",
"content-type" : "image/jpg",
"filename" : "morrowplots.jpg"
} ]
正如你所看到的,我有一個JSON項目列表/數組。我想抓取「morrowplots.jpg」文件的id並將其存儲到用於成功調用API的變量中。
因此,我將代碼設置爲如下所示。下面代碼中的結果變量是您在上面看到的JSON字符串。
case class FileName(size: String, datecreated: String, id: String, contenttype: String, filename: String)
implicit val fileReads: Reads[FileName] = (
(__ \\ "size").read[String] and
(__ \\ "datecreated").read[String] and
(__ \\ "id").read[String] and
(__ \\ "content-type").read[String] and
(__ \\ "filename").read[String]
)(FileName.apply _)
val json: JsValue = Json.parse(contentAsString(result))
val nameResult: JsResult[FileName] = json.validate[FileName](fileReads)
info("Right after validate")
nameResult match {
case s: JsSuccess[FileName] => {
val testfile: FileName = s.get
// Do something with testfile
info("Success")
}
case e: JsError => {
info("Error")
info("Errors: " + JsError.toFlatJson(e).toString())
}
}
這給了我以下錯誤。
[信息] +錯誤: { 「OBJ 大小」:[{ 「msg」 中: 「error.path.result.multiple」, 「參數」 msgid:[]}], 「OBJ文件名」 :[{「msg」:「error.path.resul t.multiple」,「args」:[]}],「obj id」:[{「msg」:「error.path.result.multiple」,, 「args」:[]}],「obj content-type」:[{「msg」:「error.path .result.multiple」,「args」:[]}],「obj * datecreated」 {「msg」:「error.path.missing」,「args」:[]}]}
那麼我該如何解決這個List/Array問題,以及如何通過文件名搜索來獲取id?
在此先感謝。