gpt4 book ai didi

json - Playframeworks json Writes implicit 需要显式类型,为什么?

转载 作者:行者123 更新时间:2023-12-02 15:32:27 24 4
gpt4 key购买 nike

这不编译:

package model

import play.api.libs.json._

case class Dog(id: Long, name: String, kind: String) {

def asJson() = Json.toJson(this)
}

object Dog {
implicit val writes = Json.writes[Dog]
}

错误:

53. Waiting for source changes... (press enter to interrupt)
[info] Compiling 1 Scala source to /Users/pablo/projects/mvp/target/scala-2.10/classes...
[error] /Users/pablo/projects/mvp/app/models/model2.scala:7: No Json deserializer found for type model.Dog. Try to implement an implicit Writes or Format for this type.
[error] def asJson() = Json.toJson(this)
[error] ^
[error] one error found
[error] (compile:compile) Compilation failed

更改伴生对象(注意显式类型):

object Dog {
implicit val writes: Writes[Dog] = Json.writes[Dog]
}

解决了这个问题。这是为什么?

最佳答案

这不是真正的答案(但我需要很多空间来粘贴我的代码!)但这对我有用:

package model

import play.api.libs.json._

object Dog {
implicit val writes = Json.writes[Dog]
}

case class Dog(id: Long, name: String, kind: String) {

def asJson() = Json.toJson(this)
}

基本上我只是将对象声明移到了类之前。这可能是由于 Json.writes 使用宏,因此必须在使用构造的 Write 实例之前发生。

关于json - Playframeworks json Writes implicit 需要显式类型,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23657978/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com