7

I have the following JSON reader in Play 2.3:

import play.api.libs.json._
import play.api.libs.json.Reads._
val airportSearchReads: Reads[String] = (JsPath \ "search").read[String](minLength(3))

and the compiler gives me the error

diverging implicit expansion for type play.api.libs.json.Reads[M]
starting with method ArrayReads in trait DefaultReads

if I use an implicit val I get

 ambiguous implicit values:
 both value uuidReads in trait DefaultReads of type => play.api.libs.json.Reads[java.util.UUID]
 and value airportSearchReads in object AirportSearch of type => play.api.libs.json.Reads[String]
 match expected type play.api.libs.json.Reads[M]

How do I get it to work?

acjay
  • 34,571
  • 6
  • 57
  • 100
elmalto
  • 1,008
  • 1
  • 14
  • 23

2 Answers2

6

I get a different error, but it works fine for me if I add an explicit type parameter to minLength:

scala> val airportSearchReads: Reads[String] = (JsPath \ "search").read[String](minLength[String](3))
airportSearchReads: play.api.libs.json.Reads[String] = play.api.libs.json.Reads$$anon$8@3fee86da

I think the problem with leaving that up to the compiler is that there are different combinations of implicits in scope that would satisfy the implicit parameter list of minLength.

acjay
  • 34,571
  • 6
  • 57
  • 100
0

DefaultReads provides readers you need for transforming json values to common types (String, Option, Array, etc.). So providing new readers for String is not necessary.

Hence, for accessing a field in your json object you don't need to define a reader, unless you want to read that field into an arbitrary type of yours.

All you need in this case is the constraint which is defined both in Reads and Constraints. So assuming that your json object is jsValue the following code gives you what you want:

// val jsValue = ...

(jsValue \ "search").as[String](Reads.minLength(3))
Nader Ghanbari
  • 4,120
  • 1
  • 23
  • 26
  • Have your removed your implicit reader? (just delete `val airportSearchReads: Reads[String] = (JsPath \ "search").read[String](minLength(3)` first). – Nader Ghanbari Nov 04 '14 at 15:03
  • still the same problem... solution on top works though, so I will use that. thank you very much for your help – elmalto Nov 04 '14 at 19:22