我正在使用 Akka Http 向第 3 方 API 发出请求。响应是“application/json”,我想使用 Akka Http 将它们转换为自定义案例类。我想做这样的事情:
val request = RequestBuilding.Get("https://service.com/v1/api/items")
val response : Future[ItemsResponse] = http.singleRequest(request).flatMap({ response =>
Unmarshal(response.entity).to[ItemsResponse]
})
这无法编译,因为我缺少类型
akka.http.scaladsl.unmarshalling.Unmarshaller[akka.http.scaladsl.model.ResponseEntity, com.mycompany.models.ItemsResponse]
的隐式解码器.我不清楚使用 akka http 执行此操作的惯用方法是什么。我知道我可以使用spray-json,但我想了解如何在不导入其他库的情况下执行此操作。 Akka Http 似乎有可能,但文档不清楚(至少对我而言)。
最佳答案
最简单的方法是使用 Spray-json 作为 Akka HTTP 的一部分:
import spray.json._
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
// change 2 to the number of attributes of ItemsResponse
implicit val ItemsResponseFormat = jsonFormat2(ItemsResponse)
这应该可以编译您现有的代码。
关于scala - Akka Http - 如何将 ResponseEntity 解码为 CustomClass?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41930164/