我正在使用 json-spray 库来解组一个 json 数组。这是代码。
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import spray.json.DefaultJsonProtocol._
def unmarshalProfiles(response: HttpResponse): Future[Array[Profile]] = {
implicit val profileFormat = jsonFormat16(Profile)
println("[RES - SUCCESS] Request returned with " + response.status)
return Unmarshal(response.entity).to[Array[Profile]]
}
远程服务器将其响应写入 json 数组。如果响应中包含一个或多个项目,则没有问题。但是,如果没有可用的 Profile 项目,则服务器返回null(不是空数组),并且在解组时我收到错误'Expected Array as JsArray, but got null'。
我认为一个不错的选择是将 Array[Profile] 包装到 Option 对象中。所以我将代码更改为以下。
def unmarshalProfiles(response: HttpResponse): Future[Option[Array[Profile]]] = {
implicit val profileFormat = jsonFormat16(Profile)
println("[RES - SUCCESS] Request returned with " + response.status)
return Unmarshal(response.entity).to[Option[Array[Profile]]]
}
尽管如此,当响应是一个空对象时,我得到了同样的错误。当它是None时,是否存在解组 Option 对象的方法?提前致谢!