case class User(username: String, password: String, role: List[Role]) extends MongoModel[User] {
.....
implicit object UserFormat extends Format[User] {
def reads(json: JsValue): User = User(
(json \ "id").as[String],
(json \ "password").as[String],
(json \ "role").asOpt[List[Role]].getOrElse(List()))
//unmarshaling to JSValue is covered in the next paragraph
def writes(u: User): JsValue = JsObject(Seq(
"username" -> JsString(u.username),
"password" -> JsString(u.password),
"role" -> JsArray(u.role.map(toJson(_)))))
}
case class Role(name: String, value: Int) extends MongoModel[Role]{
implicit object RoleFormat extends Format[Role] {
def reads(json: JsValue): Role = Role(
(json \ "name").as[String],
(json \ "value").as[Int])
//unmarshaling to JSValue is covered in the next paragraph
def writes(r: Role): JsValue = JsObject(Seq(
"name" -> JsString(r.name),
"value" -> JsNumber(r.value)))
}
}
Thanks.
It may be simpler to put them in an object (instead of in classes) and
to just import them statically.