【发布时间】:2015-01-21 18:55:31
【问题描述】:
我正在编写一些 RESTful API 测试用例,但几乎没有使用 scala playframework 的经验。
这是我的 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())
}
}
这给了我以下错误。
[信息] + 错误: {"objsize":[{"msg":"error.path.result.multiple","args":[]}],"objfilename":[{"msg":" error.path.resul t.multiple","args":[]}],"objid":[{"msg":"error.path.result.multiple","args":[]}],"objcontent-type":[{"msg":"error.path .result.multiple","args":[]}],"obj*datecreated":[{"msg":"error.path.missing","args":[]}]}
那么我该如何解决这个列表/数组问题以及如何通过文件名搜索来获取 id?
提前致谢。
【问题讨论】:
标签: arrays json scala playframework-2.2