Play Json Reads and String

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 an error

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

If I use 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 make it work?

+5
source share
2 answers

I get another 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 that before the compiler is that in the area there are different combinations of implicits that would satisfy the implicit minLength parameter minLength .

+5
source

DefaultReads provides the readers you need to convert json values ​​to regular types ( String , Option , Array , etc.). Therefore, providing new readers for String not required.

Therefore, to access a field in your json object, you do not need to define a reader if you do not want to read this field in an arbitrary type.

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

 // val jsValue = ... (jsValue \ "search").as[String](Reads.minLength(3)) 
0
source

Source: https://habr.com/ru/post/1205993/


All Articles