【发布时间】:2014-04-01 14:32:28
【问题描述】:
我有一个从 MongoDB 返回的 List[play.api.libs.json.JsObject] 具有以下文档架构:
{
"web_category_id" : "blah",
"web_category_name" : "abcabc",
"top_group_id" : "blah",
"top_group_name" : "namehere",
"sub_web_category" : [
{
"name" : "blah",
"id" : "idblah"
},
{
"name" : "another blah",
"id" : "another idblah"
}
]
}
我正在尝试使用隐式读取器将数据读入 WebCategory 案例类:
case class WebCategory(topGroupName: String,
topGroupID: String,
webCategoryName : String,
webCategoryID : String,
subWebCats:Seq[SubWebCat])
case class SubWebCat(name:String, id:String)
到目前为止,我的代码(距离编译一百万英里)是:
implicit val webCategoryReader = (
(__/ "top_group_name").read[String] and
(__/ "top_group_id").read[String] and
(__/ "web_category_name").read[String] and
(__/ "web_category_id").read[String] and
(__/ "sub_web_category").read[List[Map[String, String]].map("name", "id"))
)(WebCategory)
我什至不知道是否可以构建一个包含另一个案例类作为其值之一的案例类。
非常感谢您的帮助,谢谢!
编辑:
好的,事实证明我在 SubWebCategory 上定义了一个空白的伴随对象(出于我以外的原因)干扰了读者。可能是因为在覆盖的伴随对象中没有应用函数。有人愿意确认吗?
另外,我很昏暗,WebCategory 实际上被定义为:
case class WebCategory(topGroupName: String,
topGroupID: String,
webCategoryName : String,
webCategoryID : String,
subWebCats:Option[Seq[SubWebCat]])
所以上面特拉维斯布朗提供的答案应该是(我的错,不是他的!):
implicit val webCategoryReader: Reads[WebCategory] = (
(__ \ "top_group_name").read[String] and
(__ \ 'top_group_id).read[String] and
(__ \ 'web_category_name).read[String] and
(__ \ 'web_category_id).read[String] and
(__ \ 'sub_web_category).read[Option[List[SubWebCat]]]
)(WebCategory)
感谢您的帮助,特拉维斯
【问题讨论】:
-
除了给出的答案之外,您可能还想看看my answer here,它显示了嵌套案例类 JSON 转换的完整工作示例。