You need to enable JavaScript to run this app. 如何在Scala中通过Akka HTTP将响应实体反序列化为自定义对象
优惠活动
大模型
产品
解决方案
定价
更多

如何在Scala中通过Akka HTTP将响应实体反序列化为自定义对象

核心报错原因

编译提示找不到Unmarshaller[ResponseEntity, Profiles],本质是Akka HTTP仅内置了字符串、字节流这类基础类型的反序列化器,针对自定义业务case class的JSON反序列化逻辑,必须手动提供匹配的隐式编解码规则,否则编译器无法识别如何把JSON文本映射为自定义结构。

落地调整步骤

  • 引入和当前Akka HTTP版本完全匹配的akka-http-spray-json依赖,这是Akka HTTP对接JSON格式的官方默认桥接模块。
  • 在代码中导入必须的支持:
    import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
    import spray.json.DefaultJsonProtocol
    
  • 为两个自定义case class生成可被隐式识别的JSON格式实例:
    把编解码协议定义在伴生对象或者可访问的隐式作用域内,根据case class的字段个数选择对应参数的jsonFormat方法(spray-json内置的jsonFormat支持最多22个字段的case class):
    trait ProfileJsonProtocol extends SprayJsonSupport with DefaultJsonProtocol {
      // Profile共16个字段,对应jsonFormat16生成编解码实例
      implicit val profileFormat = jsonFormat16(Profile)
      // Profiles共1个字段,对应jsonFormat1生成编解码实例
      implicit val profilesFormat = jsonFormat1(Profiles)
    }
    

    注意:case class的字段名必须和服务端返回的JSON字段名完全匹配。你当前定义的字段都是首字母大写(如Name、Surname),如果服务端返回的JSON是小驼峰命名(如name、surname),即便编译通过,运行时也会抛出字段缺失的解析错误,需要在定义编解码规则时手动做字段映射。

  • 调整业务代码的反序列化逻辑:
    把上述定义的JSON协议引入到代码作用域内,直接将反序列化目标替换为Profiles即可。需要注意Unmarshal().to[T]本身是异步返回Future的,不要做同步阻塞调用:
    // 引入JSON协议到当前作用域
    object ClientApp extends ProfileJsonProtocol {
      def getProfiles()(implicit system: ActorSystem, ec: ExecutionContext) = {
        val req = Get("http://localhost:9090/profiles")
        val responseFuture = Http().singleRequest(req)
        responseFuture.onComplete {
          case Success(response) =>
            // 直接声明反序列化目标为Profiles类型
            val profilesFuture = Unmarshal(response.entity).to[Profiles]
            profilesFuture.onComplete {
              case Success(profiles) => 
                println(s"解析完成,共获取${profiles.profiles.size}条Profile数据")
              case Failure(parseEx) => 
                println(s"JSON解析失败:${parseEx.getMessage}")
            }
          case Failure(_) => sys.error("something wrong")
        }
      }
    }
    

常见适配场景

如果实际服务端返回的JSON直接是Profile数组(没有外层的profiles包装对象),则无需定义Profiles类,直接在协议中声明向量类型的隐式格式,将反序列化目标改为Vector[Profile]即可,无需额外调整。

内容的提问来源于stack exchange,提问作者Salvatore Calcagno

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.26 12:24:05