I am processing json in which one of the keys values
, values2
, or values3
will be a JsonObject, and the other two will be null
.
Is there any way to create a cursor such that when attempting to downField
on a json null, the resulting cursor is a failed one?
Hopefully the code example and the commented line make it clear what i'm trying to achieve here.
object Foo extends App {
import io.circe._, io.circe.parser._
val json: String = """
{
"id": "c730433b-082c-4984-9d66-855c243266f0",
"values": {
"bar": true,
"baz": 100.001
},
"values2": null
}
"""
val doc: Json = parse(json).getOrElse(Json.Null)
val rootCursor = doc.hcursor
val result = for {
name <- rootCursor.downField("id").as[String]
valuesCursor = rootCursor.downField("values")
values2Cursor = rootCursor.downField("values2")
} yield {
if (values2Cursor.succeeded) { // I want this to be false when values2 -> JNull
2
} else {
1
}
}
}
Try dropNullValues
like so
...
parse(json).getOrElse(Json.Null).dropNullValues
...
which outputs result: scala.util.Either[io.circe.DecodingFailure,Int] = Right(1)