[2.0] Trouble with implicit Json Format objects

2,015 views
Skip to first unread message

oblivion

unread,
Feb 14, 2012, 2:58:09 PM2/14/12
to play-framework
Hi,

I tried to move my Format objects to a package object to get rid of
the clutter in my controllers but the compiler throws the following
error:

No Json deserializer found for type List[Drawing]. Try to implement an
implicit Writes or Format for this type.

So the compiler does not find the object once it is moved out of the
controller where I convert my json.

I thought that a package-object would be the ideal place to put these
things.

Where else can I put them, then?

oblivion

unread,
Feb 14, 2012, 3:02:36 PM2/14/12
to play-framework
Never mind, it works now, I defined a false package statement.

Thanks for the RC !

Jay

unread,
Mar 6, 2012, 2:04:28 PM3/6/12
to play-fr...@googlegroups.com
I'm having the same issue, but my Format objects are in the same package and it won't compile "No Json deserializer found for type List[models.Role]. Try to implement an implicit Reads or Format for this type."  How did you resolve this?  My code is below

User.scala 
===============

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

  }


Role.scala
==================

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.

Julien Richard-Foy

unread,
Mar 7, 2012, 4:09:02 AM3/7/12
to play-fr...@googlegroups.com
The UserFormat and RoleFormat objects must be available in the
implicit scope of the call site.

It may be simpler to put them in an object (instead of in classes) and
to just import them statically.

danielkol

unread,
Mar 7, 2012, 4:34:59 PM3/7/12
to play-fr...@googlegroups.com
Following the example on the site, I was able to get this to work by making the UserFormat a member of object User instead of case class User
Reply all
Reply to author
Forward
0 new messages