首页 > 解决方案 > JSONDecoder 无法处理空响应

问题描述

语境

我正在使用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

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

错误

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

Swift.DecodingError.dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "JSON text没有以数组或开头允许未设置片段的对象和选项。" 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)
        }

所以很明显,即使我提供自定义 NoReply 类型(根据上面提到的帖子) JSONDecoder 不喜欢null.

有什么建议么 ?


作为旁注,这是他们的文档中关于 DELETE 操作响应的内容:

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

标签: jsonswiftfirebasefirebase-realtime-databasedecodable

解决方案


不幸的是JSONDecoder,它没有公开支持 JSON 片段(如单独值)的底层JSONSerialization选项 ( )。您可以尝试转换响应或直接使用。不幸的是,这里没有什么优雅可做的。.allowFragmentsnullJSONSerialization


推荐阅读