首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >关于未在Scala / Playframework中编译的隐式toJson函数的元组3

关于未在Scala / Playframework中编译的隐式toJson函数的元组3
EN

Stack Overflow用户
提问于 2013-09-25 17:50:54
回答 1查看 731关注 0票数 0

在Playframework中执行隐式JSON调用时,Tuple-2工作:

代码语言:javascript
复制
def toJson(itemTuple: List[((Item, ItemOption), List[Picture])]) : JsObject = { ... }

我定义了一个隐式写方法,一切都很好。在本例中,我可以在“外部”JSON块中传递类似这样的列表:

代码语言:javascript
复制
"items" -> Json.toJson(itemTupleList)

并对每个元素执行隐式方法"toJson“。但是,当我将它扩展到Tuple-3时,它失败了:

代码语言:javascript
复制
def toJson(itemTuple: List[((Item, ItemOption, ItemAttribute), List[Picture])]) : JsObject = { ... }

这产生了:

代码语言:javascript
复制
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.]

我以为我做到了:

代码语言:javascript
复制
implicit val iW = new Writes[((Item, ItemOption, ItemAttribute), List[Picture])] { ... }

原因是什么?在没有隐式方法的情况下,还有其他方法可以实现同样的目标吗(我对Scala有点陌生)。

(顺便说一句:将项目数据分成三个容器的原因是Scala的22个元组元素所依赖的。)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-09-26 11:13:11

这对我来说很管用:

代码语言:javascript
复制
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
}

代码语言:javascript
复制
% 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

确保注释您的隐含的返回类型,而不是使用推断类型。如果隐式出现在您需要的位置下面,并且返回类型不显式,编译器将不考虑它。如果是这样的话,类型推断可能会遇到令人讨厌的循环。

顺便说一句,您可以使用类型别名稍微清理代码:

代码语言:javascript
复制
 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
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19011848

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档