【问题标题】:In Play 2 how to check if a JsValue variable is NULL?在 Play 2 中如何检查 JsValue 变量是否为 NULL?
【发布时间】:2015-06-26 03:10:37
【问题描述】:

这个问题听起来可能很愚蠢,但我真的很想知道如何在 Play 2 中检查 NULL JsValue:

scala> import play.api.libs.json._
import play.api.libs.json._

scala> val json = Json.obj("a" -> true)
json: play.api.libs.json.JsObject = {"a":true}

scala> val a = json \ "nonExisting"
a: play.api.libs.json.JsValue = null

scala> a == null
res1: Boolean = false

scala> Option(a)
res2: Option[play.api.libs.json.JsValue] = Some(null)

您可以看到变量a 的值是null,但== 检查返回false。但是,以下内容按预期工作:

scala> val b: JsValue = null
b: play.api.libs.json.JsValue = null

scala> b == null
res3: Boolean = true

当我使用asOpt 进行类型转换时,它似乎又可以工作了:

scala> val c = json \ "a"
c: play.api.libs.json.JsValue = true

scala> c.asOpt[Boolean]
res4: Option[Boolean] = Some(true)

scala> a.asOpt[Boolean]
res5: Option[Boolean] = None

【问题讨论】:

  • 对我来说,您上面的情况不起作用;我不得不使用第二种解决方案来比较您的等效 b == JsNull 而不是 b == null。类型为play.api.libs.json.JsValue = nullbb == null 提供了false,但为b == JsNull 提供了true

标签: json scala playframework


【解决方案1】:

检查与play.api.libs.json.JsNull是否相等:

if (a == JsNull) { ... }

a match {
  case JsNull => ...
}

【讨论】:

  • 不幸的是,这不起作用。 a == JsNull 返回false
  • 这对我有用,在它被映射到选项之后,但我正在处理一个稍微不同的问题。对我来说,查找结果是res32: play.api.libs.json.JsLookupResult = JsDefined(null) 对象dataValue。但这似乎有效:dataValue.toOption.get == JsNull 返回了true
【解决方案2】:

如果您在 JavaScript 中尝试使用实际 JSON 执行相同的操作,通常您会得到 undefined 而不是 null。这由JsUndefined 而不是JsNull 表示。你可以寻找这个:

a.isInstanceOf[JsUndefined]

或通过使用模式匹配:

a match { case _: JsUndefined => true; case _ => false })

Scala 的强类型,准确地反映 JSON 行为有多酷!? :)

【讨论】:

  • 真的有用吗?在测试 myJsValue.isInstanceOf[JsUndefined] 时,我在编译期间收到以下警告:fruitless type test: a value of type play.api.libs.json.JsValue cannot also be a play.api.libs.json.JsUndefined
  • 不起作用。 val jsValue: JsValue = JsNull; Logger.info("jsValue.isInstanceOf[JsUndefined]: " + jsValue.isInstanceOf[JsUndefined]) --> 显示false
  • @Blackbird 那是因为 null != undefined。
  • @Blackbird Google 的 SO 问题:JavaScript 中的 null 和 undefined 有什么区别?
  • 好吧,我一定是误会了。感谢您的评论。
【解决方案3】:

我认为最好/最安全的方法是利用选项:

val a = (json \ "nonExisting").asOpt[Boolean] // Or whatever type you might expect
if (a.isEmpty) {
  println("json does not contain key: nonExisting")
} else {
  println("nonExisting value: ${a.get}")
}

【讨论】:

    猜你喜欢
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 2010-10-09
    • 2017-11-05
    • 1970-01-01
    • 2022-10-28
    • 1970-01-01
    • 2014-01-10
    相关资源
    最近更新 更多