1
我有一個案例類這樣的定義:如何爲嵌套泛型類型的對象定義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._和我的自定義協議,所以這不是問題。
編輯:我沒有導入協議,而是一個具有類似名稱的類。歡迎編程! :)至少有人可能會從中受益。