Compile error while returning chunked response from play 2.8.18.

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

Compile error while returning chunked response from play 2.8.18

问题

  1. 我正在尝试在Play框架中使用分块响应。
  2. 以下控制器代码正常运行。
  3. def chunkedSample = Action {
  4. val source = Source.apply(List("Hello","Hai"))
  5. Ok.chunked(source)
  6. }
  7. 但当我将List对象更改为如下的案例类时
  8. def chunkedSample = Action {
  9. val source = Source.apply(List(Dummy("hello")))
  10. Ok.chunked(source)
  11. }
  12. 我得到以下编译错误
  13. `找不到参数writable的隐式值:Writable[Dummy]`
  14. 我尝试将json格式和写入放在下面的伴随对象中,但没有起作用。
  15. object Dummy{
  16. implicit val write = Json.writes[Dummy]
  17. }
英文:

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

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

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

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

Where I define dummy case class as below

  1. 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.

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

答案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.

  1. case class Dummy(hello: String)
  2. implicit lazy val dummyReads: Reads[Dummy] = (
  3. (__ \ "hello").read[String]
  4. )(Dummy)
  5. implicit lazy val dummyWrites: Writes[Dummy] = (
  6. (__ \ "hello").write[String]
  7. )(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.

  1. case class Dummy(hello: String)
  2. implicit lazy val dummyReads: Reads[Dummy] = (
  3. (__ \ "hello").read[String]
  4. )(Dummy)
  5. implicit lazy val dummyWrites: Writes[Dummy] = (
  6. (__ \ "hello").write[String]
  7. )(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:

确定