1

I have two classes, and each of them contains the other:

import play.api.libs.json.Json

case class Param(name: String,
                 data: ParamData)
case class ParamData(`type`: String,
                     value: String,
                     options: Option[List[Param]])

implicit val paramDataJsonFormat = Json.format[ParamData]
implicit val paramJsonFormat = Json.format[Param]

when I define the Json format I get a compilation error:

Error:(110, 51) No implicit format for List[Param]] available.

implicit val paramJsonFormat = Json.format[Param]

If I change the order of the implicits I get the same error on the other line:

Error:(110, 51) No implicit format for List[ParamData]] available.

implicit val paramDataJsonFormat = Json.format[ParamData]

How can I solve this?

Community
  • 1
  • 1
tano
  • 836
  • 1
  • 10
  • 25
  • 1
    How are you gonna instantiate one of this classes? The only way I see would be to add a `null` in one of the two or an empty list in `ParamData`. – Ende Neu Jan 26 '16 at 14:09
  • @EndeNeu You're right. The `options` member of `ParamData` is optional. I'll edit the question. Thanks – tano Jan 26 '16 at 14:12
  • 1
    That doesn't change what I was hinting to though, usually when I end up with cyclic references it's because there's a flaw in my design, in your case even if you use options, you still can have a `None` or a `Some` with an empty list, as you can see there's much difference. – Ende Neu Jan 26 '16 at 14:14
  • Suppose you have to model a menu item with an object. A menu item has a name and (optionally) a series of sub-items. How would you model it avoiding cyclic references? – tano Jan 26 '16 at 14:21
  • I admit I've never encountered this situation but it makes sense. You need then to write your own format (`new Format[Param] {...} `), and manually handle the case where there is a `None`, a `Some` and empty and non empty list. you cannot use the macro expansion for this. – Ende Neu Jan 26 '16 at 14:35

1 Answers1

1

Found the solution in the Play official documentation. There is a specific section regarding recursive types I was missing.

tano
  • 836
  • 1
  • 10
  • 25
  • Maybe it helps somebody https://stackoverflow.com/questions/55255292/play-json-serialize-deserialize-mutual-recursive/55256753#55256753 – kapranov.anton Mar 20 '19 at 08:52