I have a sample code as below.
import play.api.libs.json._
import play.api.libs.functional.syntax._
import play.api.data.validation.ValidationError
import play.api.libs.json.Reads._
case class Retailer(firstName:String,lastName:String,email:String,mobileNo:String,password:String)
case class Business(name:String,preferredUrl:String,businessPhone:String,retailer:Retailer)
object JsonTest {
val jsonValue = """
{
"business":
{
"name":"Some Business Name",
"preferredUrl":"someurl",
"businessPhone":"somenumber",
"retailer":
{
"firstName":"Some",
"lastName":"One",
"email":"[email protected]",
"mobileNo":"someothernumber",
"password":"$^^HFKH*"
}
}
}
"""
def printJson ={
implicit val rltRds = (
(__ \ "firstName").read[String] ~
(__ \ "lastName").read[String] ~
(__ \ "email").read[String] ~
(__ \ "mobileNo").read[String] ~
(__ \ "password").read[String]
)(Retailer)
implicit val bsnsRds = (
(__ \ "name").read[String] ~
(__ \ "preferredUrl").read[String] ~
(__ \ "businessPhone").read[String] ~
(__ \ "retailer").read[Retailer](rltRds)
)(Business)
val buisness = Json.parse(jsonValue).validate[Business](bsnsRds)
val bus = new Business("Some Business","somebusinessurl","somenumber", new Retailer("Some","One","[email protected]","someothernumber","$^^HFKH*"))
//val json = Json.toJson(bus)
println(buisness)
}
def main(args: Array[String]): Unit = {
printJson
}
}
I get Json Validation Error when I try to parse the json into Scala object (Business Class in this case). The error is
JsError(List((/retailer,List(ValidationError(validate.error.missing-path,WrappedArray()))), (/preferredUrl,List(ValidationError(validate.error.missing-path,WrappedArray()))), (/name,List(ValidationError(validate.error.missing-path,WrappedArray()))), (/businessPhone,List(ValidationError(validate.error.missing-path,WrappedArray())))))
However if my json is like
val jsonValue = """
{
"name":"Some Business Name",
"preferredUrl":"someurl",
"businessPhone":"somenumber",
"retailer":
{
"firstName":"Some",
"lastName":"One",
"email":"[email protected]",
"mobileNo":"someothernumber",
"password":"$^^HFKH*"
}
}
"""
Note that the outer bracket "{" and the "business:" key are removed. I get a JsSuccess. How do I write the reads for the Json as in the first case? Also, how can I do it in a generic way?
Please help.
Just add the business
key in the path:
implicit val bsnsRds = (
(__ \ "business" \ "name").read[String] ~
(__ \ "business" \ "preferredUrl").read[String] ~
(__ \ "business" \ "businessPhone").read[String] ~
(__ \ "business" \ "retailer").read[Retailer](rltRds)
)(Business)
Slight variation to the above:
implicit val bsnsRds = ({
val business = (__ \ "business")
(business \ "name").read[String] ~
(business \ "preferredUrl").read[String] ~
(business \ "businessPhone").read[String] ~
(business \ "retailer").read[Retailer](rltRds)
})(Business)
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