0

Say I have a model like this:

case class Items(typeOfItems: TypeOfItems)

object Items{
  implicit val format = Json.format[Items]
}


sealed trait TypeOfItems extends Product with Serializable

object TypeOfItems {

  final case class Toy(typeOfItem : String, name : String, price : Int) extends TypeOfItems

  final case class Car(typeOfItem : String, model: String, price : Int ) extends TypeOfItems

}

I cannot do any serialising or deserialising. I get the following errors:

 No instance of play.api.libs.json.Format is available for model.TypeOfItems in the implicit scope (Hint: if declared in the same file, make sure it's declared before)
[error]   implicit val format = Json.format[Items]
[error]                                    ^
[error]  No Json serializer found for type model.Items. Try to implement an implicit Writes or Format for this type.
[error]     Ok(Json.toJson(Items(Toy("Toy", "Doll", 2))))

I am not sure how to specify the formats for TypeOfItems. How do I do that?

Mojo
  • 1,152
  • 1
  • 8
  • 16
  • Play json support sealed trait, but there implicit for `Json.format[Items]` is missing (play doesn't auto materialize to avoid recursive lookup issue in some Scala version) – cchantep Nov 05 '19 at 17:20

1 Answers1

0

In Play 2.7 sealed traits are supported in play-json.

As already mentioned in comments all you are missing is:

object TypeOfItems{
  implicit val format = Json.format[TypeOfItems]
}

See here the requirements in the documentation: ScalaJsonAutomated

For Play 2.6 see this answer: Noise free JSON format for sealed traits with Play 2.2 library (as the title suggests there are also solutions for older versions)

pme
  • 14,156
  • 3
  • 52
  • 95