【问题标题】:Scala. How to Unmarshall Option values using json spray?斯卡拉。如何使用 json spray 解组选项值?
【发布时间】:2021-01-07 15:15:02
【问题描述】:

我正在使用 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 (不是空数组),并且在解组时我收到错误 'Expected Array as JsArray,但为空'

我认为一个不错的选择是将 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 em>时,是否存在一个选项对象的方法? 提前致谢!

【问题讨论】:

    标签: json scala unmarshalling spray-json scala-option


    【解决方案1】:

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

    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(...)

    【讨论】:

      猜你喜欢
      • 2013-12-29
      • 2015-09-26
      • 2015-04-16
      • 2012-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-25
      相关资源
      最近更新 更多