Compile error while returning chunked response from play 2.8.18.

huangapple go评论138阅读模式
英文:

Compile error while returning chunked response from play 2.8.18

问题

我正在尝试在Play框架中使用分块响应。
以下控制器代码正常运行。

    def chunkedSample = Action {
      val source = Source.apply(List("Hello","Hai"))
      Ok.chunked(source)
    }

但当我将List对象更改为如下的案例类时

    def chunkedSample = Action {
      val source = Source.apply(List(Dummy("hello")))
      Ok.chunked(source)
    }

我得到以下编译错误
`找不到参数writable的隐式值:Writable[Dummy]`
我尝试将json格式和写入放在下面的伴随对象中,但没有起作用。

    object Dummy{
      implicit val write = Json.writes[Dummy]
    }
英文:

I am trying out chunked response in play framework.
The below controller code works fine.

def chunkedSample = Action {
  val source = Source.apply(List("Hello","Hai"))
  Ok.chunked(source)
}

But when I change the List object to a case class as below

def chunkedSample = Action {
  val source = Source.apply(List(Dummy("hello")))
  Ok.chunked(source)
}

Where I define dummy case class as below

case class Dummy(hello:String)

I get below compilation error
No implicit found for parameter writable:Writable[Dummy]
I tried putting json format & writes in companion object below but didn't work.

object Dummy{
  implicit val write = Json.writes[Dummy]
}

答案1

得分: 1

The error tells you that you are missing writes, so you need to add them. There are different ways to add them, but for case class I find next example as most convenient. It also has read as you will most probably need it in the future.

case class Dummy(hello: String)

implicit lazy val dummyReads: Reads[Dummy] = (
  (__ \ "hello").read[String]
)(Dummy)

implicit lazy val dummyWrites: Writes[Dummy] = (
  (__ \ "hello").write[String]
)(unlift(Dummy.unapply))

More documentation could be found on this page of Play framework official docs.

英文:

The error tells you that you are missing writes, so you need to add them. There are different ways to add them, but for case class I find next example as most convenient. It also has read as you will most probably need it in the future.

case class Dummy(hello: String)

implicit lazy val dummyReads: Reads[Dummy] = (
  (__ \ "hello").read[String]
)(Dummy)

implicit lazy val dummyWrites: Writes[Dummy] = (
  (__ \ "hello").write[String]
)(unlift(Dummy.unapply))

More documentation could be found on this page of Play framework official docs.

huangapple
  • 本文由 发表于 2023年4月10日 21:09:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75977421.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定