简体   繁体   中英

Combine JSON Reads in Play 2.1

I have 2 reads. One is user. User is a subset of the main read called Registration.

{
 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
}

Registration: package models

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

case class Registration( 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 _)
}

Ultimately I want User to be it's own seperate object. I want to be able to use User in multiple other reads so it needs to be more modular. Is this possible?

Bonus: Can user serialize each field into seperate variables or a hashmap instead of a tuple?

You can extract User and use it again anywhere you want:

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM