2017-04-02 62 views
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._和我的自定义协议,所以这不是问题。

编辑:我没有导入协议,而是一个具有类似名称的类。欢迎编程! :)至少有人可能会从中受益。

回答

1

傻我,我输入了错误的类型。一旦我导入了正确的类型,这个工作。希望代码可以帮助其他人。