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

标签 scala generics akka-http spray-json

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

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/

相关文章:

scala - 带有 akka : Providing implicit actorSystem to several layers 的蛋糕图案

scala - activiti中Identity链接类型的区别

java - 这个通用语法是什么意思?

java - 是否可以拥有一个带有一个指定类型参数和一个泛型类型参数的 Java 接口(interface)?

java - 单元/集成测试由通用方法组成的 dao

scala - 将 Akka Http 服务的一些 Path Parameters 更改为 Query Params

scala - Akka Http Server - 如何让路由响应字节数组二进制响应

scala - 带有时间戳字段的Elasticsearch和Spark写错误

斯卡拉。部分类

json - 使用 Akka Http 和 Circe 在 Scala 中解码 JSON