Search code examples
scalaplay-json

How to create an empty JsResult in play json?


I am writing an implicit reads returning JsResult[Seq[T]] based on a condition:

some_condition match{
     case Some(value) => // JsResult[Seq[T]]
     case _ => // returning an empty JsResult here of similar type?
}

What would be the way for return such JsResult?


Solution

  • You will need to use the method validate, which returns JsResult. There are 2 case classes that inherits JsResult:

    1. JsSuccess
    2. JsError

    Therefore you can consider the following example:

    case class T()
    implicit val reads = Json.reads[T]
    val jsValue: JsValue = ...
    
    jsValue.validate[Seq[T]] match {
      case JsSuccess(t, path) =>
        println(t)
      case JsError(errors) =>
        println(errors)
    }