0

I'm not able to get the following to work, so don't know if it's even possible:

case class ItemA(name:String,itemB:ItemB)
case class ItemB(name:String)

object ToJson{
   implicit val itemAJson = Json.format[ItemA]
   implicit val itemBJson = Json.format[ItemB]
}

I get a compile error of something like:

No implicit format for ItemB available. [error] implicit val itemAJson = Json.format[ItemA]

Pretty sure it can't be done, but is there a sensible approach to take?

Play Framework 2.3

kdr
  • 57
  • 5
  • As your ItemA depends on ItemB so in order to create json.Format[ItemA] there must be defined json.Forma[ItemB] first, hence change the order first define itemBJson then itemAJson – grotrianster Sep 18 '15 at 13:40
  • This fixed it. Want to add it as an answer and I can confirm that? – kdr Sep 18 '15 at 13:45

2 Answers2

2

As your ItemA depends on ItemB so in order to create json.Format[ItemA] there must be defined json.Forma[ItemB] first, hence change the order first define itemBJson then itemAJson

implicit val itemBJson = Json.format[ItemB]
implicit val itemAJson = Json.format[ItemA]
grotrianster
  • 2,368
  • 12
  • 14
0

Another option is to lazy the implicit variables ... in this way it does not affect the order you write it. I have many jsonFormat and they all work correctly like this:

object ToJson {
   implicit lazy val itemAJson = Json.format[ItemA]
   implicit lazy val itemBJson = Json.format[ItemB]
}

Similar is the solution in the Play documentation. for recursive types.