使用Sttp与Circe将Json反序列化为自定义对象遇解码错误求助
问题分析与解决方案
你的核心问题是HTTP返回的JSON是一个数组(包含单个MyResponse对象),但你用的是单个MyResponse类型的解码器,解码器解析数组时找不到.id字段(因为当前解析的顶层结构是数组,不是对象)。
解决步骤:
1. 调整sttp响应的目标类型
把asJson[MyResponse]改成asJson[List[MyResponse]],匹配返回的数组结构:
basicRequest.(...).get(...).response(asJson[List[MyResponse]].getRight).send(backend).map { responseList => // 根据业务场景处理数组,比如取第一个元素(推荐用headOption避免空数组报错) responseList.headOption }
2. 确保解码器作用域正确
如果解码器定义在局部代码块,要保证它在sttp调用的代码可见范围内。更稳妥的方式是把解码器放在样例类的伴生对象里,让circe自动识别:
import io.circe.Decoder import io.circe.generic.semiauto.deriveDecoder case class Other(name: String, age: Int) object Other { implicit val decoder: Decoder[Other] = deriveDecoder[Other] } case class MyResponse(id: String, name: String, others: List[Other]) object MyResponse { implicit val decoder: Decoder[MyResponse] = deriveDecoder[MyResponse] }
可选:兼容API返回数组但期望单个对象的场景
如果确认API原本应该返回单个MyResponse对象却错误返回了数组,可以自定义解码器适配:
implicit val decoderMyResponse: Decoder[MyResponse] = Decoder[List[MyResponse]].emap { case single :: Nil => Right(single) case Nil => Left("Empty response array") case multiple => Left(s"Expected single element, got ${multiple.size}") }
这样就能直接解析成单个MyResponse对象,同时处理数组格式的返回结果。
内容的提问来源于stack exchange,提问作者Developus
相关产品推荐
相关产品推荐

