我正在使用Reactivemongo驱动程序(使用Scala)编写Play 2.3.2应用程序。 我有存储所有用户数据的recommendation.user集合。 一份文件具有以下形式:
{
"_id" : ObjectId("542e67e07f724fc2af28ba75"),
"id" : "",
"email" : "luigi@gmail.com",
"tags" : [
{
"tag" : "Paper Goods:Liners - Baking Cups",
"weight" : 2,
"lastInsert" : 1412327492874
},
{
"tag" : "Vegetable:Carrots - Jumbo",
"weight" : 4,
"lastInsert" : 1412597883569
},
{
"tag" : "Paper Goods:Lialberto- Baking Cups",
"weight" : 1,
"lastInsert" : 1412327548205
},
{
"tag" : "Fish:Swordfish Loin Portions",
"weight" : 3,
"lastInsert" : 1412597939124
},
{
"tag" : "Vegetable:Carrots - alberto@gmail.com",
"weight" : 2,
"lastInsert" : 1412597939124
}
]
}
现在我正在编写一个返回特定用户的所有标签的方法。 我回复了JSOn的回应。 在游戏中如何创建动态json? 我的回归json有以下形式:
{
"tags": [
{"tag": "tag1"},
{"tag": "tag2"}
]
}
这是我的方法实现:
def userTag(user: String) = Action.async {
//obtain all the users saved in the db.
val allUser : Future[Option[User]] = Users.find(Json.obj("email" -> user)).one
val futureComputation = allUser map {
(user: Option[User]) =>
user match {
case Some(x) => x.tags match {
case Some(userTags) => val tags: List[Tag] = userTags.map{tag: (Tag, Double, Long) => tag._1} //obtain all the Tag objects
//here for every element in the tags variable i want to add it add the json.
case None => Ok(Json.obj()) //return an empty json.
}
case None => Ok(Json.obj()) //return an empty json
}
}
futureComputation
}
我如何解决我的问题?
答案 0 :(得分:0)
解决使用:
def userTag(user: String) = Action.async {
//obtain all the users saved in the db.
val allUser : Future[Option[User]] = Users.find(Json.obj("email" -> user)).one
val futureComputation = allUser map {
(user: Option[User]) =>
user match {
case Some(x) => x.tags match {
case Some(userTags) => val tags = userTags.map{tag: (Tag, Double, Long) => val t = tag._1; t.category + ":" + t.attr} //obtain all the Tag objects
val arrayTags = for(tag <- tags) yield{Json.obj("tag" -> tag)} //crete the array json
Ok(Json.obj("tags" -> arrayTags)) //return the json corresponding to the user.
case None => Ok(Json.obj()) //return an empty json.
}
case None => Ok(Json.obj()) //return an empty json
}
}
//return the Future computation JSON responce.
futureComputation
}