在Play 2.1中结合JSON读取

时间:2013-04-04 15:38:06

标签: json scala playframework-2.1

我有2次读取。一个是用户。用户是主要读取的子集,称为注册。

{
 user: {
  id: "35fc8ba5-56c3-4ebe-9a21-489a1a207d2e",
  username: "flastname",
  first_name: "FirstName",
  last_name: "LastName",
  email_address: "first@foobar.com",
  user_avatar: "http://blog.ideeinc.com/wp-content/uploads/2010/04/tineye-robot.jpg"
 },
 activity_type: 8
}

注册: 包装模型

导入play.api.libs.json._ import play.api.libs.functional.syntax ._

案例类注册(         user :( String,String,String,String,String,String),         activityType:Int )

object Registration {
    implicit val regReads: Reads[Registration] = (
      (__ \ "user").read(
        (__ \ "id").read[String] ~
        (__ \ "username").read[String] ~
        (__ \ "first_name").read[String] ~
        (__ \ "last_name").read[String] ~
        (__ \ "email_address").read[String] ~
        (__ \ "user_avatar").read[String]
        tupled
      ) ~
      (__ \ "activity_type").read[Int]
      )(Registration.apply _)
}

最终我希望用户成为它自己的独立对象。我希望能够在多个其他读取中使用User,因此它需要更加模块化。这可能吗?

加分:用户可以将每个字段序列化为单独的变量或散列映射而不是元组吗?

1 个答案:

答案 0 :(得分:3)

您可以提取User并在任何地方再次使用它:

case class User(id: String, username: String, firstName: String, lastName: String, email: String, avatar: String)
case class Registration(user: User, activityType: Int)

object Implicits{
  implicit val userReads = (
    (__ \ "id").read[String] ~
    (__ \ "username").read[String] ~
    (__ \ "first_name").read[String] ~
    (__ \ "last_name").read[String] ~
    (__ \ "email_address").read[String] ~
    (__ \ "user_avatar").read[String]
  )(User)

  implicit val regReads = (
    (__ \ "user").read[User] ~
    (__ \ "activity_type").read[Int]
  )(Registration)    
}

import Implicits._
Json.fromJson[Registration](json).asOpt.toString
//Some(Registration(User(35fc8ba5-56c3-4ebe-9a21-489a1a207d2e,flastname,FirstName,LastName,first@foobar.com,http://blog.ideeinc.com/wp-content/uploads/2010/04/tineye-robot.jpg),8))