Convert JsValue to String

Reading this article, I cannot figure out how to convert my Some(JsValue) to a string.

Example:

 val maybeString: Option[JsValue] = getSomeJsValue(); // returns Some(JsValue) val str: String = maybeString match { case Some(x) => x.as[String] case _ => "0" } 

runtime error:

 play.api.Application$$anon$1: Execution exception[[JsResultException: JsResultException(errors:List((,List(ValidationErr or(validate.error.expected.jsstring,WrappedArray())))))]] at play.api.Application$class.handleError(Application.scala:289) ~[play_2.10.jar:2.1.3] 
+6
source share
2 answers

You want to create several options for flatMap:

 maybeString flatMap { json => json.asOpt[String] map { str => // do something with it str } } getOrElse "0" 

Or as a for understanding:

 (for { json <- maybeString str <- json.asOpt[String] } yield str).getOrElse("0") 

I would also advise working with the value inside the map and passing the parameter around, so that None will be processed by your controller and displayed on BadRequest , for example.

+5
source

Your mistake comes from the fact that you did not impose a sufficient condition on type x: maybeString is Option[JsValue] , not Option[JsString] . If maybeString not Option[JsString] , the conversion fails and an exception is thrown.

You can do it:

 val str: String = maybeString match { case Some(x:JsString) => x.as[String] case _ => "0" } 

Or you can use asOpt[T] instead of as[T] , which returns Some(_.as[String]) if the conversion was successful, None otherwise.

+3
source

Source: https://habr.com/ru/post/952782/


All Articles