I am trying to parse a json using play framework into a case class. My intention here is to check whether a particular path exists in the json. If exists then only read element at that path.
Here is my code
package com.learning.avinash.query
import play.api.libs.json.{JsDefined, JsPath, Json, Reads, Writes, __}
import play.api.libs.functional.syntax._
object ParseJson extends App {
case class Msisdn(primaryId: Option[String], relatedAccountId: Option[String])
object Msisdn {
implicit val readData: Reads[Msisdn] = (
(JsPath \ "primary-id").readNullable[String] ~
(JsPath \ "meta" \ "related-account-id").readNullable[String]
) (Msisdn.apply _)
}
val testJson = """{
"resources": [
{
"valid-for-start-datetime": "2019-08-23T10:47:17.485Z",
"primary-id": "393823468684",
"meta": {
"related-account-id": "10001771",
"roles": [
"customer"
]
}
},
{
"valid-for-start-datetime": "2019-08-23T10:47:17.485Z",
"primary-id": "393823467689"
}
]
}"""
println((Json.parse(testJson) \ "resources").as[List[Msisdn]])
}
In the resources array in the second object you can observe this code is completely missing
"meta": {
"related-account-id": "10001771",
"roles": [
"customer"
]
}
Now when i try to parse the json, it fails and i get the following exception
Exception in thread "main" play.api.libs.json.JsResultException: JsResultException(errors:List(((1)/meta/related-accoount-id,List(JsonValidationError(List(error.path.missing),WrappedArray())))))
Is there a predefined function/method in play so that i can check whether this
(JsPath \ "meta")
particular path exists and then only read the element in that path. Or should i write a custom function to check whether the path exists.
I could see a JsDefined() which expects a Jsvalue.
https://www.playframework.com/documentation/2.7.x/api/scala/play/api/libs/json/index.html
final case classJsDefined(value: JsValue)
Wrapper for JsValue to represent an existing Json value.
Any thoughts, ideas, help or suggestions please.
accoount(related-accoount-id). It is not reason of exception, of course