我正在写一个JSON
Writes
. 在models/Users.scala,
我定义了一个implicit
带有定义的对象implicit
。
object UserImplicits {
/*Writes (write to JsValue) are used by toJson method of Json object to convert data (say the model) to JsValue*/
implicit val profileWrites:Writes[UserProfile] = (
(JsPath \ "confirmed").write[Boolean] and
(JsPath \ "email").write[String] and
(JsPath \ "firstname").write[String] and
(JsPath \ "lastname").write[String]
) (unlift(UserProfile.unapply))
implicit val userWrites: Writes[User] = (
(JsPath \ "id").write[UUID] and
(JsPath \ "user-profile").write[UserProfile]
) (unlift(User.unapply))
implicit val usersResourceWrites:Writes[UsersResource] = (
(JsPath \ "id").write[String] and
(JsPath \ "url").write[String] and
(JsPath \ "user").write[User]
) (unlift(UsersResource.unapply))
/*Reads (read from JsValue) is used by Json object's as or asOpt methods to convert JsValue to some other data, eg your model*/
implicit val profileReads:Reads[UserProfile] = (
(JsPath \ "confirmed").read[Boolean] and
(JsPath \ "email").read[String] and
(JsPath \ "firstname").read[String] and
(JsPath \ "lastname").read[String]
) (UserProfile.apply _)
implicit val userReads: Reads[User] = (
(JsPath \ "id").read[UUID] and
(JsPath \ "user-profile").read[UserProfile]
) (User.apply _)
implicit val usersResourceReads: Reads[UsersResource] = (
(JsPath \ "id").read[String] and
(JsPath \ "url").read[String] and
(JsPath \ "user").read[User]
) (UsersResource.apply _)
}
在我的controller
课堂上,我已经导入models._
并定义了控制器,如下所示:
import models._
import scala.concurrent.{ExecutionContext, Future}
class UserController @Inject()(cc: ControllerComponents)(implicit exec: ExecutionContext) extends AbstractController(cc){
//TODOM - remove hard coded response
def addUser = Action.async{ implicit request => {
println("addUser controller called")
val user = User(UUID.randomUUID(),UserProfile(true,"m@m.com","m","c"))
val userResource = UsersResource(user.id.toString(),"/ws/users",user)
val json = Json.toJson(userResource); //converts the model to JsValue using Writes defined in Users model class
println("returning json:",Json.prettyPrint(json))
Future{Ok(json)}}
}
我收到以下编译错误。
No Json serializer found for type models.UsersResource. Try to implement an implicit Writes or Format for this type.
对于代码val json = Json.toJson(userResource);
问题似乎是 Play 找不到隐式写入。如果我在控制器中移动隐式定义而不是在模型中定义,则代码有效。如何使 model/user.scala 中定义的隐式在控制器类中可见?