我想做这样的事情:
(request.body \ "optional-integer").toOption[Int]
如果正文中没有optional-integer
字段,我将得到一个None
,否则为整数值。
有什么惯用的方法吗?
最佳答案
(request.body \ "optional-integer").asOpt[Int]
应该做的工作。这使用 JsValue
.asOpt()
,其中
Tries to convert the node into a T.
比较 the JSON basics manual, part Using JsValue.as/asOpt
val nameOption = (json \ "name").asOpt[String] // Some("Watership Down") val bogusOption = (json \ "bogus").asOpt[String] // None
关于scala - 使用 Play Json 将可选的 json 字段转换为选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38853404/