如何编写Scala Play框架自定义类的多个JSON序列化器解串器?

时间:2015-02-20 09:07:43

标签: json scala serialization playframework deserialization

我有以下类需要序列化反序列化器

 case class User(userId: Int, userName: String, email: String,        
 password: String) {

 def this() = this(0, "", "", "")

def this(userId: Int){
this(userId, "", "", "" )
}

def this(userId: Int, userName: String){
  this(userId, userName, "", "" )
}

def this(userId: Int, userName: String, email: String){
  this(userId, userName,email, "" )
}

def this(password: String){
  this(0, "","", password )
 }
}

我有多个构造函数的用户案例类。这样可以将用户创建为

  1. var u =新用户(mid,mname,memail,mpassword)
  2. var u =新用户(mid,mname)
  3. 我期待JSON请求为

    JSON请求类型1: -

     "teamMembers" : [ {
        "userId" : 1,
        "userName" : "user name",
        "email" : "eamil",
        "password" : "password"
      }, {
        "userId" : 2,
        "userName" : "user name 2",
        "email" : "email2",
        "password" : "pssword"
      } ]
    

    OR JSON请求类型1: -

    "teamMembers" : [ {
        "userId" : 1,
        "userName" : "user name"
      }, {
        "userId" : 2,
        "userName" : "user name 2"
      } ]
    

    我实现了JSON序列化器反序列化器,它仅对第一类请求

    工作正常
      trait UserJson extends Controller {
      implicit val userWrites: Writes[User] = (
          (__ \ "userId").write[Int] ~
          (__ \ "userName").write[String] ~
          (__ \ "email").write[String] ~
          (__ \ "password").write[String]
        )(unlift(User.unapply))
    
       implicit val userReads: Reads[User] = (
          (__ \ "userId").read[Int](min(0) keepAnd max(150)) ~
          (__ \ "userName").read[String](minLength[String](2)) ~
          (__ \ "email").read[String](minLength[String](2)) ~
          (__ \ "password").read[String](minLength[String](2))
        )(User.apply _)
    } 
    

    但是对于类型2,JSON请求不起作用。你能告诉我如何申请2型JSON请求吗?提前谢谢!

2 个答案:

答案 0 :(得分:1)

您可以将Json读取/写入用作隐式值

例如:

Json.toJson(user)(userWrites1)
Json.toJson(user)(userWrites2)

答案 1 :(得分:0)

听起来像emailpasswordOptional。您可以将emailpassword设置为Option并使用writeNullable,如下所示。那是你在找什么?

旁注:您的this def看起来很奇怪,在Scala中,您通常会使用apply来实现这一目标。

case class User(userId: Int, userName: String, email: Option[String],  password: Option[String])

implicit val userWrites: Writes[User] = (
  (__ \ "userId").write[Int] ~
  (__ \ "userName").write[String] ~
  (__ \ "email").writeNullable[String] ~
  (__ \ "password").writeNullable[String]
)(unlift(User.unapply))