我正在阅读https://www.playframework.com/documentation/2.0.4/ScalaJsonGenerics
SearchResult[T]
示例正是我想要的,但是我在编译时遇到了错误:
导入play.api.libs.json ._
case class SearchResults[T](
elements: List[T],
page: Int,
pageSize: Int,
total :Int
)
object SearchResults
{
implicit def searchResultsReads[T](implicit fmt: Reads[T]): Reads[SearchResults[T]] = new Reads[SearchResults[T]] {
def reads(json: JsValue): SearchResults[T] = new SearchResults[T] (
(json \ "elements") match {
case JsArray(ts) => ts.map(t => Json.fromJson(t)(fmt))
case _ => throw new RuntimeException("Elements MUST be a list")
},
(json \ "page").as[Int],
(json \ "pageSize").as[Int],
(json \ "total").as[Int]
)
}
implicit def searchResultsWrites[T](implicit fmt: Writes[T]): Writes[SearchResults[T]] = new Writes[SearchResults[T]] {
def writes(ts: SearchResults[T]) = JsObject(Seq(
"page" -> JsNumber(ts.page),
"pageSize" -> JsNumber(ts.pageSize),
"total" -> JsNumber(ts.total),
"elements" -> JsArray(ts.elements.map(Json.toJson(_)))
))
}
}
我有以下编译错误:
Error:(17, 14) constructor cannot be instantiated to expected type;
found : play.api.libs.json.JsArray
required: play.api.libs.json.JsLookupResult
case JsArray(ts) => ts.map(t => Json.fromJson(t)(fmt))
答案 0 :(得分:0)
方法fromJson
和toJson
是在类中定义的方法:
play.api.libs.json.Json