scala 将 JsValue 转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18519913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting JsValue to String
提问by Kevin Meredith
Reading through this article, I can't figure out how to convert my Some(JsValue)to a String.
通读这篇文章,我不知道如何将 my 转换Some(JsValue)为 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: 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]
采纳答案by Marius Soutier
You want to compose multiple Options, that's what flatMap is for:
你想组合多个选项,这就是 flatMap 的用途:
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 BadRequestfor example.
我还建议使用地图中的值并传递 Option ,因此 None 将由您的控制器处理并映射到BadRequest例如。
回答by Marth
Your error comes from the fact that you don't impose enough condition on x's type : maybeStringis an Option[JsValue], not Option[JsString]. In the case maybeStringis not an Option[JsString], the conversion fails and raises and exception.
您的错误来自于您没有对 x 的类型强加足够的条件 : maybeStringis an Option[JsValue], not Option[JsString]。如果maybeString不是Option[JsString],则转换失败并引发异常。
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, Noneotherwise.
或者您可以使用asOpt[T]代替as[T],Some(_.as[String])如果转换成功None则返回,否则返回。

