Customizing JSON serialization in Play

后端 未结 3 833
灰色年华
灰色年华 2020-12-10 23:29

I\'m using renderJSON(Object) to return some objects as JSON values, and it\'s working fine except for one field. Is there an easy way to add in that one field

3条回答
  •  一整个雨季
    2020-12-10 23:59

    After evaluating the play framework we hit a stumbling block and decision choice on serializing JSON for an external API. Allot of articles out there suggest using the Lift framework within play which just seem like extra overhead.After trying some of the frameworks / modules with in the play framework a college and myself decided to write a light weight code block that could cater for our needs.

    case class User (
        user_id:        Int,
        user_name:      Option[String],
        password:       Option[String],
        salt:           Option[String]
    ) extends Serializable {
      def toXml = 
        
              {user_id}
              {user_name.getOrElse("")}
        
    
      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.map(u => u.toXml) }
            
        }
    
        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)
        }
    
    
    
      }
    

提交回复
热议问题