I am trying to pass this json string to my other method but SOMETIMES I get this error,
play.api.libs.json.JsResultException: JsResultException(errors:List((,List(ValidationError(error.expected.jsstring,WrappedArray())))))
I find it strange that this occurs randomly, sometimes I don't get the exception and sometimes I do. Any ideas?
Here is what my json looks like
val string = {
"first_name" : {
"type" : "String",
"value" : "John"
},
"id" : {
"type" : "String",
"value" : "123456789"
},
"last_name" : {
"type" : "String",
"value" : "Smith"
}
}
I read it like
(string \ "first_name").as[String]
(string \ "first_name")
gives JsValue
not JsString
so as[String]
does not work.
But if you need first name value
you can do
val firstName = ((json \ "first_name") \ "value").as[String]
This is another option to consider for type safety while reading and writing Json with play Json API. Below I am showing using your json as example reading part and writing is analogous.
Represent data as case classes.
case Person(id:Map[String,String], firstName:Map[String,String], lastName:[String,String]
Write implicit read/write for your case classes.
implicit val PersonReads: Reads[Person]
Employ plays combinator read API's. Import the implicit where u read the json and you get back the Person object. Below is the illustration.
val personObj = Json.fromJson[Person](json)
Please have a look here https://www.playframework.com/documentation/2.6.x/ScalaJsonAutomated
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With