如何在 play json 中创建一个空的 JsResult?

How to create an empty JsResult in play json?

我正在写一个隐式读取 returning JsResult[Seq[T]] 基于条件:

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

return这样的JsResult会怎样?

您将需要使用方法 validate, which returns JsResult。有 2 个案例 类 继承 JsResult:

  1. JsSuccess
  2. JsError

因此你可以考虑下面的例子:

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)
}