2014-10-06 25 views
0

我正在寫一個Play 2.3.2應用程序使用Reactivemongo驅動程序(與斯卡拉)。 我推薦了一個存儲所有用戶數據的推薦用戶集合。 一號文件的格式如下:創建一個動態的JSON與播放

{ 
"_id" : ObjectId("542e67e07f724fc2af28ba75"), 
    "id" : "", 
    "email" : "[email protected]", 
    "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 - [email protected]", 
      "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

使用解決:

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 

    }