After evaluating the playback platform, we will click on the stumbling block and choose a solution for serializing JSON for the external API. Highlighting articles there involves using the Lift framework in the game, which just seems like an unnecessary overhead. After trying some frameworks / modules in the gaming infrastructure, college and I decided to write a block of light weight code that could satisfy our needs,
case class User ( user_id: Int, user_name: Option[String], password: Option[String], salt: Option[String] ) extends Serializable { def toXml = <user> <user_id>{user_id}</user_id> <user_name>{user_name.getOrElse("")}</user_name> </user> override def toJson = "{" + JSON.key("user_id") + JSON.value(user_id) + ", " + JSON.key("user_name") + JSON.value(user_name) + "}" } class Serializable { def toJson = "" } object JSON { def key(x:String) = value(x) + ": " def value(x:Any):String = { x match { case s:String => "\"" + s + "\"" case y:Some[String] => value(y.getOrElse("")) case i:Int => value(i.toString) case s:Serializable => s.toJson case xs:List[Any] => "[" + xs.map(x => value(x)).reduceLeft(_ + ", " + _) + "]" } } } def searchUserByName(user_name: String) = { (for ( u <- Users if u.user_name.like(("%"+user_name+"%").bind) ) yield u.*) .list .map(User.tupled(_)) } def toXml(users:List[User]) = { <users> { users.map(u => u.toXml) } </users> } def toJson(users:List[User]) = { "[" + users.map(u => u.toJson).reduceLeft(_ + ", " + _) + "]" }
And from the controller.
// -- http://localhost:9000/api/users/getUser/xml // -- http://localhost:9000/api/users/getUser/json def getUser(requestType:String) = { db withSession{ val user = Users.byUserName("King.Kong") if(requestType == "xml") { Xml(user.toXml) } else { user.toJson } } } //--- http://localhost:9000/api/users/searchuser/xml //--- http://localhost:9000/api/users/searchuser/json def searchUser(requestType:String) = { db withSession{ val users = Users.searchUserByName("Doctor.Spoc") if(requestType == "xml") { Xml(Users.toXml(users)) } else { val jsonList = Users.toJson(users) Json(jsonList) } }
source share