diff --git a/play-json/shared/src/main/scala/play/api/libs/json/JsLookup.scala b/play-json/shared/src/main/scala/play/api/libs/json/JsLookup.scala index 152b59afa..a5f7420ba 100644 --- a/play-json/shared/src/main/scala/play/api/libs/json/JsLookup.scala +++ b/play-json/shared/src/main/scala/play/api/libs/json/JsLookup.scala @@ -195,9 +195,10 @@ case class JsDefined(value: JsValue) extends AnyVal with JsLookupResult * Represent a missing Json value. */ final class JsUndefined(err: => String) extends JsLookupResult { - def error = err - def validationError = JsonValidationError(error) - override def toString = s"JsUndefined($err)" + def error = err + def validationError = JsonValidationError(error) + override def toString = s"JsUndefined($err)" + override def asOpt[T](implicit fjs: Reads[T]): Option[T] = None } object JsUndefined { diff --git a/play-json/shared/src/test/scala/play/api/libs/json/JsLookupSpec.scala b/play-json/shared/src/test/scala/play/api/libs/json/JsLookupSpec.scala new file mode 100644 index 000000000..e0a368552 --- /dev/null +++ b/play-json/shared/src/test/scala/play/api/libs/json/JsLookupSpec.scala @@ -0,0 +1,27 @@ +/* + * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. + */ + +package play.api.libs.json + +import play.api.libs.json.Json._ + +import org.scalatest.matchers.must.Matchers +import org.scalatest.wordspec.AnyWordSpec + +class JsLookupSpec extends AnyWordSpec with Matchers { + "JsLookupResult" should { + val obj = Json.obj( + "field" -> 123 + ) + val result = obj \ "missingField" + + "return JsUndefined when a key is missing" in { + result mustBe a[JsUndefined] + } + + "return None when calling asOpt on JsUndefined" in { + result.asOpt[Int].mustEqual(None) + } + } +}