scalaplay-json

Scala Play List[Any] to JsArray


I have a List[Any] which I want to convert to a JsArray.

List with type works:

Json.arr(List("1"))

But:

Json.arr(List("1").asInstanceOf[List[Any]])

throws:

diverging implicit expansion for type play.api.libs.json.Reads[T1]
starting with method oFormatFromReadsAndOWrites in object OFormat

How can I convert List[Any] to JsArray?

I tried:

implicit val listAnyFormat: OFormat[List[Any]] = Json.format[List[Any]]

But I get thrown with:

No instance of Reads is available for scala.collection.immutable.Nil in the implicit scope 

Using Play 2.8.x and Scala 2.11.8


Solution

  • You can't.

    At least not without defining a Format[Any] which can be done technically but will likely not cover all the possible cases.

    The question is why do you have a List[Any] in the first place? It has not much sense in Scala world.

    It would be better if you could have a List[Something] where Something has a known set of subtypes and each of them has a Format.