我有一个具有此定义的案例类:
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/