Search code examples
scalaplayframeworkplay-json

No Instance of play.api.libs.json.Format is availablefor scala.collection.immutable.List[Item]


Note: I'm very new to PlayFramework.

I'm trying to serialise an item object into a JSON String. I receive the following error:

 No instance of play.api.libs.json.Format is available for 
 scala.collection.immutable.List[Item] in the implicit scope (Hint: if declared
 in the same file, make sure it's declared before)

 [error]   implicit val itemRESTFormat: Format[ItemREST] = 
 Json.format[ItemREST]

I really don't understand what the error means at all, or have any idea what is going wrong. If someone could explain to me what the error means, and what the potential issue could be, that would be great. Thanks!

import...

case class ItemREST(items: List[Item]) {
    def toJson: String = Json.toJson(this).as[JsObject].toString()
}

object ItemREST {
    implicit val itemRESTFormat: Format[ItemREST] = Json.format[ItemREST]

    def fromItem(items: List[Item]): ItemREST = {
        ItemREST(items)
    }
}

Solution

  • In your code, the ItemREST has list of elements of type Item. Hence for serializing ItemREST, serializer for Item is required.

    object Item {
      implicit val itemFormat = Json.format[Item]
    }
    
    object ItemREST {
      implicit val itemRESTFormat: Format[ItemREST] = Json.format[ItemREST]
    }
    

    You just need to declare the serializer of Item before ItemREST and that will solve your problem.

    Also, one thing that you could try out is to add the

    implicit val itemFormat = Json.format[Item]
    

    just before the

      implicit val itemRESTFormat: Format[ItemREST] = Json.format[ItemREST]
    

    The complete code would look like this

    case class Item(i : Int)
    case class ItemList(list : List[Item])
    
    object ItemList{
      implicit  val itemFormat = Json.format[Item]
      implicit  val itemListFormat = Json.format[ItemList]
    }
    
    
    object SOQ extends App {
    
      println(Json.toJson(ItemList(List(Item(1),Item(2)))))
    
    }
    

    giving you n output as

    {"list":[{"i":1},{"i":2}]}