gpt4 book ai didi

scala - 如何为具有嵌套泛型类型的对象定义 JSON 格式?

转载 作者:行者123 更新时间:2023-12-04 17:52:46 27 4
gpt4 key购买 nike

我有一个具有此定义的案例类:

case class EndpointResponse[A](timestamp: Instant, uuid: UUID, content: A)

case class User(id: UUID, username: String, email: String)

以及具有以下定义的 JsonFormat:

trait EndpointsJsonProtocol extends DefaultJsonProtocol {

implicit def endpointResponseJsonFormat[A: JsonFormat] = new RootJsonFormat[EndpointResponse[A]] {
val dtFormatter = DateTimeFormatter.ISO_INSTANT

override def write(response: EndpointResponse[A]): JsValue = response match {
case _: EndpointResponse[_] => JsObject(
"timestamp" -> JsString(dtFormatter.format(response.timestamp)),
"uuid" -> JsString(response.uuid.toString), // note we don't encode to slug on purpose
"content" -> response.content.toJson
)
case x => deserializationError("Deserialization not supported " + x)
}

override def read(value: JsValue): EndpointResponse[A] = value match {
case JsObject(encoded) =>
value.asJsObject.getFields("timestamp", "uuid", "content") match {
case Seq(JsString(timestamp), JsString(uuid), content) =>
EndpointResponse(Instant.from(dtFormatter.parse(timestamp)), UUID.fromString(uuid), content.convertTo[A])
case x => deserializationError("Unable to deserialize from " + x)
}
case x => deserializationError("Unable to deserialize from " + x)
}
}

implicit def userResponseFormat: JsonFormat[User] = jsonFormat3(User.apply)
}

/** JsonProtocol 的单例 */对象 EndpointsJsonProtocol 扩展了 EndpointsJsonProtocol

现在,当我尝试将简单类型转换为 json 作为内容时,它工作正常。

EndpointResponse(uuid, user).toJson

但是当我用嵌套的泛型尝试它时,它不会编译。

val records: List[User] = // not relevant
EndpointResponse(uuid, records).toJson

知道我在这里做错了什么吗?提前致谢。我已经导入了 spray.json._ 和我的自定义协议(protocol),所以这不是问题。

编辑:我没有导入协议(protocol),而是导入了一个具有相似名称的类。欢迎来到编程! :) 至少有人可以从中受益。

最佳答案

愚蠢的我,我导入了错误的类型。一旦我导入了正确的类型,这就有效了。希望代码可以帮助别人。

关于scala - 如何为具有嵌套泛型类型的对象定义 JSON 格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43170789/

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