简体   繁体   English

播放Json Reads和String

[英]Play Json Reads and String

I have the following JSON reader in Play 2.3: 我在Play 2.3中有以下JSON阅读器:

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 如果我使用implicit val我得到

 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? 我如何让它工作?

I get a different error, but it works fine for me if I add an explicit type parameter to minLength : 我得到一个不同的错误,但如果我向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 . 我认为将其留给编译器的问题是,在范围内存在不同的implicits组合,它们将满足minLength的隐式参数列表。

DefaultReads provides readers you need for transforming json values to common types ( String , Option , Array , etc.). DefaultReads为读者提供了将json值转换为常用类型( StringOptionArray等)所需的读者。 So providing new readers for String is not necessary. 因此,不需要为String提供新的读者。

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. 因此,为了访问json对象中的字段,您不需要定义读取器,除非您想将该字段读入您的任意类型。

All you need in this case is the constraint which is defined both in Reads and Constraints . 在这种情况下,您所需要的只是在ReadsConstraints定义的Constraints So assuming that your json object is jsValue the following code gives you what you want: 因此,假设您的json对象是jsValue ,以下代码为您提供了所需内容:

// val jsValue = ...

(jsValue \ "search").as[String](Reads.minLength(3))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM