Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play Framework 2.2: No Json deserializer found

My format, reads and writes methods don't work and I'm not able to locate the problem. In my opinion I implemented Json.format, Json.reads and Json.writes as expected. If I compile my code I get the following error:

No Json deserializer found for type Option[(String, String, String, String, String)]

My Model:

object User {

    val simple = {
        get[Option[Long]]("id") ~
        get[String]("username") ~
        get[String]("email") ~
        get[String]("firstname") ~
        get[String]("lastname") map {
        case id ~ username ~ email ~ firstname ~ lastname => User(
          id, username, email, firstname, lastname)
      }
    }

  implicit val userFormatter = Json.format[User]
  implicit val userReads = Json.reads[User]
  implicit val userWrites = Json.writes[User]

    def findById(id: Long): Option[User] = {
      DB.withConnection {
        implicit connection =>
          SQL("select * from \"user\" where id = {id}").on('id -> id).as(User.simple.singleOpt)
      }
    }
}

My Action:

def get(id: Long) = Action {
    Ok(Json.toJson(User.findById(id).map {
      user =>
        (user.id.toString, user.username, user.email, user.firstname, user.lastname)
    }).getOrElse[String](""))
  }
like image 388
trollr Avatar asked Nov 12 '22 18:11

trollr


1 Answers

Json.toJson[T](obj: T) takes an implicit Writes[T] (which Format[T] implements).

You then transform an Option[User] to an Option[Tuple5[String, String, String, String, String]] and give that to toJson so it the compiler tries to find such a Format/Writes. Probably not what you intended.

What you want is probably something like this:

def get(id: Long) = Action {
  User.findById(id)
   .map(user => Ok(Json.toJson(user)))
   .getOrElse(BadRequest(s"Unknown user $id"))
}
like image 196
johanandren Avatar answered Nov 15 '22 12:11

johanandren