Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting JsValue to String

Reading through this article, I can't 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"
}

run-time 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]
like image 217
Kevin Meredith Avatar asked Aug 29 '13 19:08

Kevin Meredith


People also ask

What is a JSValue?

You use the JSValue class to convert basic values, such as numbers and strings, between JavaScript and Objective-C or Swift representations to pass data between native code and JavaScript code.


2 Answers

You want to compose multiple Options, that's what flatMap is for:

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

Or as a for comprehension:

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

I'd also advise to work with the value inside the map and pass the Option around, so a None will be handled by your controller and mapped to a BadRequest for example.

like image 95
Marius Soutier Avatar answered Oct 26 '22 21:10

Marius Soutier


Your error comes from the fact that you don't impose enough condition on x's type : maybeString is an Option[JsValue], not Option[JsString]. In the case maybeString is not an Option[JsString], the conversion fails and raises and exception.

You could do this :

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

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

like image 39
Marth Avatar answered Oct 26 '22 20:10

Marth