1
votes

I am using Play Framework 2.3 Json request coming to my controller from U.I containing list of integers

i want to validate and parse it to scala list so i am using implicit Reads

the problem i am facing is that when i implement my Read with only list like this

case class MgsValidation(  mgsidlist : List[Int]) 
object MgsValidation{
  implicit val readmgs : Reads[MgsValidation] = (
      (JsPath \ "mgslist").read[List[Int]]
      )(MgsValidation.apply _)
}

i get following error

overloaded method value read with alternatives:

[error] (t: List[Int])play.api.libs.json.Reads[List[Int]]

[error] (implicit r: play.api.libs.json.Reads[List[Int]])play.api.libs.json.Reads[List[Int]]

[error] cannot be applied to (List[Int] => models.JsonParsing.MgsValidation)

[error] (JsPath \ "mgslist").read[List[Int]]

but if I add any other random parameter like this

case class MgsValidation( uuid :Int , mgsidlist : List[Int]) 
object MgsValidation{
  implicit val deleteread : Reads[MgsValidation] = (
      (JsPath \ "uuid").read[Int] and
      (JsPath \ "mgslist").read[List[Int]]
      )(MgsValidation.apply _)
}

it works fine

but i want to simply validate and parse only List

how can i do this?

and also please tell me why is this Reads works fine with more than one parameter?

1

1 Answers

2
votes

There is a trick here: when you are using the combinator and your expression don't have the same type when you don't.

scala> :t (JsPath \ "mgslist").read[List[Int]]
play.api.libs.json.Reads[List[Int]]

but:

scala> :t ((JsPath \ "mgslist").read[List[Int]] and (JsPath \ "mgslist").read[List[Int]])
play.api.libs.functional.FunctionalBuilder[play.api.libs.json.Reads]#CanBuild2[List[Int],List[Int]] = play.api.libs.functional.FunctionalBuilder$CanBuild2@134e0422

The second type have the corresponding apply method defined on it, so you can just pass the case class' apply function afterwards. On the other side, Reads have map and flatMap defined on it, so you should use map to transform a Reads[List[Int]] to a Reads[MsgValidation]:

  (JsPath \ "mgslist").read[List[Int]].map(MgsValidation.apply _)