gpt4 book ai didi

scala - 使用 Play Json 将可选的 json 字段转换为选项?

转载 作者:行者123 更新时间:2023-12-02 04:39:14 26 4
gpt4 key购买 nike

我想做这样的事情:

(request.body \ "optional-integer").toOption[Int]

如果正文中没有optional-integer 字段,我将得到一个None,否则为整数值。有什么惯用的方法吗?

最佳答案

作为@Mikesname's comment说,

(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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com