斯卡拉。如何使用json解组选项值?

斯卡拉。如何使用json解组选项值?,json,scala,unmarshalling,spray-json,scala-option,Json,Scala,Unmarshalling,Spray Json,Scala Option,我使用json spray库来解组json数组。 这是代码 import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._ import spray.json.DefaultJsonProtocol._ def unmarshalProfiles(response: HttpResponse): Future[Array[Profile]] = { implicit val profileFormat =

我使用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数组。如果响应中包含一个或多个项目,则没有问题。但是,如果没有可用的配置文件项,服务器将返回null(不是空数组),在解组时,我会得到错误“预期数组为JsArray,但得到null”

我认为一个好的选择是将数组[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]]]
      }
尽管如此,当响应是空对象时,我还是得到了相同的错误。 当选项对象为无时,是否存在解组选项对象的方法?
提前谢谢

您可以选择与选项一起工作。这意味着,要这样定义您的方法:

def unmarshalProfiles(response: HttpResponse)(implicit mat: Materializer): Future[Option[Array[Profile]]] = {
  implicit val profileFormat = jsonFormat16(Profile)
  Unmarshal(Option(response.entity)).to[Option[Array[Profile]]]
}
然后
null
将被编组为
None
,现有数组将成为
Some(…)