You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala ZIO-HTTP如何返回自定义响应对象?

在ZIO-HTTP中返回自定义对象作为HTTP响应的正确做法

要在ZIO-HTTP中返回自定义对象,核心是利用ZIO-JSON将对象编码为JSON格式,再封装到HTTP响应中。以下是具体实现步骤:

1. 确保依赖与导入正确

首先确认项目引入了zio-http和zio-json的兼容依赖(以sbt为例):

libraryDependencies ++= Seq(
  "dev.zio" %% "zio-http" % "2.0.0", // 替换为你使用的ZIO-HTTP版本
  "dev.zio" %% "zio-json" % "0.6.2"   // 匹配对应版本的ZIO-JSON
)

同时在代码中导入ZIO-JSON的核心包:

import zio.json._

2. 正确编码自定义对象

你已定义的样例类和Codec是有效的,但Response.json()无法直接接收自定义对象,需要先将对象编码为JSON格式。

方式一:利用现有Codec编码

你的Codec包含完整的编解码逻辑,直接调用toJson方法即可将对象转为JSON字符串:

Http.collect[Request] { 
  case Method.GET -> !! / "customer" => 
    val customer = CustomerResponse(1, "a", 1)
    Response.json(customer.toJson) // 将对象转为JSON字符串后传入Response.json
}

方式二:直接定义JsonEncoder(更轻量)

如果仅需要编码功能(无需解码),可以直接派生JsonEncoder而非全量Codec,代码更简洁:

final case class CustomerResponse(id: Int, name: String, age: Int)

object CustomerResponse {
  implicit val responseEncoder: JsonEncoder[CustomerResponse] = deriveEncoder[CustomerResponse]
}

之后同样可以通过customer.toJson生成JSON字符串,部分ZIO-HTTP版本还支持借助隐式JsonEncoder直接传入对象:

Response.json(CustomerResponse(1, "a", 1))

3. 处理编码错误(可选)

如果需要处理编码过程中可能出现的异常(如对象结构不符合JSON规范),可以使用toJsonEither方法获取编码结果,再转换为响应:

import zio._

Http.collectZIO[Request] { 
  case Method.GET -> !! / "customer" => 
    val customer = CustomerResponse(1, "a", 1)
    customer.toJsonEither match {
      case Right(json) => ZIO.succeed(Response.json(json))
      case Left(error) => ZIO.succeed(Response.status(Status.InternalServerError).text(s"编码失败: $error"))
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 17:51:29