简体   繁体   中英

Scala Play - Json Parse


I am receiving a JSON from an external service and my goal is to parse it exactly as it is.
The main issue is this: a value can be nullable or it can be absent BUT null has different meaning of absent. So I want to catch this somehow.
For example this JSON:

{
  "a": null,
  "b": 1
}

is different from this one:

{
  "b": 1
}

Can you help me please?

UPDATE:
Sorry for the delay in the update. Anyway: you are right, I have a implicit custom reads in the middle and currently I use "a".readNullable[Double] and "a".write[Option[Double]] and case class is something like:

case class Example(a: Option[Double])

Just laying out what @mfirry was talking about with a detailed example (play-json 2.6):

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

scala> val json1 = Json.parse("""{"a": null, "b": 1}""")
json1: play.api.libs.json.JsValue = {"a":null,"b":1}

scala> val json2 = Json.parse("""{"b": 1}""")
json2: play.api.libs.json.JsValue = {"b":1}

scala> (json1 \ "a").isDefined
res8: Boolean = true

scala> (json1 \ "a") == JsDefined(JsNull)
res3: Boolean = true

scala> (json2 \ "a").isDefined
res7: Boolean = false

scala> (json2 \ "a")
res5: play.api.libs.json.JsLookupResult = JsUndefined('a' is undefined on object: {"b":1})

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