Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

scala - 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...