在 Play 2 中如何检查 JsValue 变量是否为 NULL?

In Play 2 how to check if a JsValue variable is NULL?

这个问题可能听起来很愚蠢,但我真的很想知道如何在 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 检查 returns。然而,以下按预期工作:

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

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

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

a match {
  case JsNull => ...
}

如果您在 JavaScript 中尝试与实际 JSON 相同的操作,通常您会得到 undefined 而不是 null。这由 JsUndefined 而非 JsNull 表示。您可以改为查找:

a.isInstanceOf[JsUndefined]

或通过使用模式匹配:

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

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

我认为 best/safest 方法是利用选项:

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}")
}