简体   繁体   中英

Play Framework - migration from version 2.3.x to 2.4.1: how to determine whether a JSON value is JsUndefined

I'm trying to migrate my Play application from version 2.3.8 to 2.4.1... but I'm still facing some issues.

I use play-json-zipper , which always returns a JsValue ... and thus the following statement doesn't work with Play 2.4.1:

import play.api.libs.json._
import play.api.libs.json.extensions._

val json = JsObject(...)

val v = json.get(__ \ 'key) match { // json.get returns a JsValue
  case _: JsUndefined => Seq[JsValue]()
  case js: JsValue => js.as[JsArray].value
}

In Play 2.4.1 JsUndefined doesn't inherit from JsValue (they both inherit from JsReadable ). My code is quite huge... and removing play-json-zipper would imply a considerable effort. Is there a workaround to determine whether the JsValue returned by json.get(__ \\ 'key) is undefined?

That's an interesting one. The commit says "JsUndefined should not be a JsValue". That's fair enough, I think it makes better sense for it to use the Some/None approach instead.

If you want to do exactly what you wrote there, can use something like this:

val v: Seq[JsValue] = (json \ "key").toOption.map {
  case JsArray(els) => els
  case _ => Seq[JsValue]()
} getOrElse(Seq[JsValue]())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM