I’m trying to deserialize a JsArray into a List[T] in a playframework application using Scala. After some research I found this method which is supposed to do the needed work:
/**
* Deserializer for List[T] types.
*/
implicit def listReads[T](implicit fmt: Reads[T]): Reads[List[T]] = new Reads[List[T]] {
def reads(json: JsValue) = json match {
case JsArray(ts) => ts.map(t => fromJson(t)(fmt)).toList
case _ => throw new RuntimeException("List expected")
}
}
The problem is that I didn’t know how to use it. Any help is welcome.
Here’s a quick example:
And if you have a custom type with a
Formatinstance:It still works:
This approach would also work if your custom type had a
xs: List[String]member, for example: you’d just use(json \ "xs").as[List[String]]in yourreadsmethod andJson.toJson(foo.xs)in yourwrites.