我试图从看起来像这样的JSON文件中提取数据:
val json: JsValue = Json.parse("""
{
"item": {
"id" : "11111111",
"name" : "box",
"categories" : [{
"name" : "blue box",
"id" : "12345",
},
{
"name" : "fancy box",
"id" : "98765",
}]
}
}
""")
我想使用play JSON库来完成它。我想出了这段代码:
//I define my class and reader for one category
case class ItemCategory(id: Option[String], name: String)
implicit val categoryRead: Reads[ItemCategory] = (
(JsPath \ "item" \ "categories" \ "id").readNullable[String] and
(JsPath \ "item" \ "categories" \ "name").read[String]
)(ItemCategory.apply _)
//I define my class and reader for one item
case class MyItem(categories : Option[List[ItemCategory]], id : Option[String], name : Option[String])
implicit val myItemRead: Reads[MyItem] = (
(JsPath \ "item" \ "categories").readNullable[List[ItemCategory]] and
(JsPath \ "item" \ "id").readNullable[String] and
(JsPath \ "item" \ "name").readNullable[String]
)(MyItem.apply _)
//I then try to read :
var item: JsResult[MyItem] = json.validate[MyItem](myItemRead)
println(item)
但是这段代码给出了一个JsError:List(ValidationError(validate.error.missing-path,WrappedArray())).
我的理解仅仅意味着某些路径缺失。我试着只阅读一个类别,它工作正常,我尝试阅读一个项目,而不是试图得到类别,这里又一次很好。因此我认为问题在于阅读项目清单。如果你能帮助我,我真的很感激。
答案 0 :(得分:1)
路径是相对的。 categoryRead js路径应该是相对的。例如_ \ xxx