Akka http-如何将ResponseEntity解包到CustomClass? [英] Akka Http - How to Unmarshall ResponseEntity to CustomClass?

查看:0
本文介绍了Akka http-如何将ResponseEntity解包到CustomClass?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Akka http向第三方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的惯用方法是什么。我知道我可以使用sprap-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)

这应该会编译您的现有代码。

这篇关于Akka http-如何将ResponseEntity解包到CustomClass?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆