在Scala Play中进行读写以获取自定义类的列表 [英] Making Reads and Writes in Scala Play for lists of custom classes
问题描述
所以我的项目中有两个班级
So I have two classes in my project
case class Item(id: Int, name: String)
和
case class Order(id: Int, items: List[Item])
我正在尝试对Order进行读写属性,但出现编译器错误,提示:
I'm trying to make reads and writes properties for Order but I get a compiler error saying:
未找到unapply或unapplySeq函数"
"No unapply or unapplySeq function found"
在我的控制器中,我有以下内容:
In my controller I have the following:
implicit val itemReads = Json.reads[Item]
implicit val itemWrites = Json.writes[Item]
implicit val listItemReads = Json.reads[List[Item]]
implicit val listItemWrites = Json.writes[List[Item]]
该代码适用于itemReads
和itemWrites
,但不适用于底部的两个.谁能告诉我我要去哪里错了,我是Play框架的新手.
The code works for itemReads
and itemWrites
but not for the bottom two. Can anyone tell me where I'm going wrong, I'm new to Play framework.
谢谢您的时间.
推荐答案
"No unapply or unapplySeq function found
"错误是由以下两个原因引起的:
The "No unapply or unapplySeq function found
" error is caused by these two:
implicit val listItemReads = Json.reads[List[Item]]
implicit val listItemWrites = Json.writes[List[Item]]
把它们扔掉. 如恩德所说,Play知道如何处理列表.
Just throw them away. As Ende said, Play knows how to deal with lists.
但是对于Order
,您也需要Reads
和Writes
!而且由于您同时进行阅读和书写,因此定义 Format
,这是Reads
和Writes
特征的混合.这应该起作用:
But you need Reads
and Writes
for Order
too! And since you do both reading and writing, it's simplest to define a Format
, a mix of the Reads
and Writes
traits. This should work:
case class Item(id: Int, name: String)
object Item {
implicit val format = Json.format[Item]
}
case class Order(id: Int, items: List[Item])
object Order {
implicit val format = Json.format[Order]
}
上面,排序很重要; Item
和伴随对象必须在Order
之前.
Above, the ordering is significant; Item
and the companion object must come before Order
.
因此,一旦您拥有所有需要的隐式转换器,关键是在控制器中使其正确可见.上面是一种解决方案,但是还有其他方法,正如我在尝试做类似的事情之后了解到的.
So, once you have all the implicit converters needed, the key is to make them properly visible in the controllers. The above is one solution, but there are other ways, as I learned after trying to do something similar.
这篇关于在Scala Play中进行读写以获取自定义类的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!