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._ 导入 play.api.libs.functional.syntax._

案例类注册(用户:(字符串,字符串,字符串,字符串,字符串,字符串),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 成为它自己的单独对象。我希望能够在多个其他读取中使用用户,因此它需要更加模块化。这可能吗?

奖励:用户可以将每个字段序列化为单独的变量或哈希图而不是元组吗?

4

1 回答 1

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))
于 2013-04-07T12:07:48.017 回答