Reputation: 1322
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: "[email protected]",
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?
Upvotes: 1
Views: 991
Reputation: 3441
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,[email protected],http://blog.ideeinc.com/wp-content/uploads/2010/04/tineye-robot.jpg),8))
Upvotes: 3