JSONDecoder 无法处理空响应

Nic*_*ick 4 json firebase swift firebase-realtime-database decodable

语境

我正在使用Firebase 数据库 REST API和 JSONDecoder/JSONEncoder。到目前为止,它一直运行良好。但是,对于删除数据,预期返回的响应是null,而 JSONDecoder 似乎不太喜欢那样。

这是我通过 Postman 发送的查询类型以及我返回的内容(不包括敏感数据)。

DELETE /somedata/-LC03I3oHcLhQ/members/ZnWsJtrZ5UfFS6agajbL2hFlIfG2.json
content-type: application/json
cache-control: no-cache
postman-token: ab722e0e-98ed-aaaa-bbbb-123f64696123
user-agent: PostmanRuntime/7.2.0
accept: */*
host: someapp.firebaseio.com
accept-encoding: gzip, deflate
content-length: 39


HTTP/1.1 200
status: 200
server: nginx
date: Thu, 02 Aug 2018 21:53:27 GMT
content-type: application/json; charset=utf-8
content-length: 4
connection: keep-alive
access-control-allow-origin: *
cache-control: no-cache
strict-transport-security: max-age=31556926; includeSubDomains; preload

null
Run Code Online (Sandbox Code Playgroud)

如您所见,响应代码是200,正文是null

错误

当我收到响应时,这是我得到的错误:

Swift.DecodingError.dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data is not valid JSON.",underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "JSON text not start with array or对象和允许未设置片段的选项。” UserInfo={NSDebugDescription=JSON 文本未以数组或对象开头,并且允许未设置片段的选项。}))))

我尝试NoReply按照之前的帖子创建自定义类型 ( ) 来处理此问题,但无济于事。

代码

这是发生错误的地方:

        resource: {
            let decoder = JSONDecoder()
            decoder.dateDecodingStrategy = .iso8601
            return try decoder.decode(Resource.self, from: $0)
        },
        error: {
            let decoder = JSONDecoder()
            return try decoder.decode(FirebaseError.self, from: $0)
        }
Run Code Online (Sandbox Code Playgroud)

因此,显然即使我提供自定义 NoReply 类型(根据上面提到的帖子)JSONDecoder 也不喜欢null.

有什么建议 ?


作为旁注,这是他们的文档关于 DELETE 操作的响应的说明:

成功的 DELETE 请求由 200 OK HTTP 状态代码指示,响应包含 JSON null

Nic*_*ick 6

快速跟进

经过几次成功的黑客攻击后,我想出的最优雅的解决方案是以下组合:

  • 使用(如ZoulNoReply所描述)
  • 将字符串转换null为空 JSON 对象结构 ( {})

首先,转换:

            if "null" == String(data: data, encoding: .utf8) {
                let json = Data("{}".utf8)
Run Code Online (Sandbox Code Playgroud)

然后反馈给处理请求响应的闭包:

        resource: {
            let decoder = JSONDecoder()
            return try decoder.decode(Resource.self, from: $0)
        },
Run Code Online (Sandbox Code Playgroud)

其中资源不是别人,而是:

公共结构NoReply:可解码{}

现在效果很好,允许我处理返回的不存在对象上的 DELETE 情况和 GET 情况null

谢谢您的帮助 !


Jon*_*ier 5

不幸的是JSONDecoder,没有公开支持 JSON 片段的基础JSONSerialization选项 ( .allowFragments),就像一个单独的null值。您可以尝试转换响应或直接使用JSONSerialization。不幸的是,这里没有什么优雅的事情要做。