在Playframework中执行隐式JSON调用时,Tuple-2工作:
def toJson(itemTuple: List[((Item, ItemOption), List[Picture])]) : JsObject = { ... }我定义了一个隐式写方法,一切都很好。在本例中,我可以在“外部”JSON块中传递类似这样的列表:
"items" -> Json.toJson(itemTupleList)并对每个元素执行隐式方法"toJson“。但是,当我将它扩展到Tuple-3时,它失败了:
def toJson(itemTuple: List[((Item, ItemOption, ItemAttribute), List[Picture])]) : JsObject = { ... }这产生了:
sbt.PlayExceptions$CompilationException: Compilation error[No Json deserializer found for type List[(models.butik.Item, models.butik.ItemOption, models.butik.ItemAttribute)]. Try to implement an implicit Writes or Format for this type.]我以为我做到了:
implicit val iW = new Writes[((Item, ItemOption, ItemAttribute), List[Picture])] { ... }原因是什么?在没有隐式方法的情况下,还有其他方法可以实现同样的目标吗(我对Scala有点陌生)。
(顺便说一句:将项目数据分成三个容器的原因是Scala的22个元组元素所依赖的。)
发布于 2013-09-26 11:13:11
这对我来说很管用:
import play.api.libs.json._
object Scratch {
def main(args: Array[String]): Unit = {
println(toJson(List(((1, 2, 3), List(3)))))
}
def toJson(itemTuple: List[((Item, ItemOption, ItemAttribute), List[Picture])]) : JsValue =
Json.toJson(itemTuple)
implicit val iW: Writes[((Item, ItemOption, ItemAttribute), List[Picture])] = new Writes[((Item, ItemOption, ItemAttribute), List[Picture])] {
def writes(x: ((Item, ItemOption, ItemAttribute), List[Picture])) = Json.parse("[1, 2, 3, [3]]") // TODO
}
type Item = Int
type ItemOption = Int
type ItemAttribute = Int
type Picture = Int
}。
% cat build.sbt
scalaVersion := "2.10.2"
libraryDependencies ++= Seq(
"com.typesafe.play" %% "play-json" % "2.2.0-RC2"
)
resolvers += "Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/"
% sbt run
[info] Loading project definition from /Users/jason/code/scratch4/project
[info] Set current project to scratch4 (in build file:/Users/jason/code/scratch4/)
[info] Running scratch.Scratch
[[1,2,3,[3]]]
[success] Total time: 0 s, completed Sep 26, 2013 1:16:21 PM确保注释您的隐含的返回类型,而不是使用推断类型。如果隐式出现在您需要的位置下面,并且返回类型不显式,编译器将不考虑它。如果是这样的话,类型推断可能会遇到令人讨厌的循环。
顺便说一句,您可以使用类型别名稍微清理代码:
def toJson(itemTuple: List[Record]): JsValue =
Json.toJson(itemTuple)
implicit def recordWrite: Writes[Record] = new Writes[Record] {
def writes(rec: Record) = {
Json.parse("{}") // TODO
}
}
type Record = ((Item, ItemOption, ItemAttribute), List[Picture])
type Item = Int
type ItemOption = Int
type ItemAttribute = Int
type Picture = Int
}https://stackoverflow.com/questions/19011848
复制相似问题