json - 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
。
解决方案
不幸的是JSONDecoder
,它没有公开支持 JSON 片段(如单独值)的底层JSONSerialization
选项 ( )。您可以尝试转换响应或直接使用。不幸的是,这里没有什么优雅可做的。.allowFragments
null
JSONSerialization
推荐阅读
- json - 在从 json 调用的命令中包含空格
- c# - 在 MVC 中创建图表返回 System.NotSupportedException
- c# - 确定站点正在使用的 Angular/AngularJS 版本的最快和最好的方法是什么?
- ios - 如何在 Iphone 上设置不透明动画?
- javascript - Selenium 不会点击最上面的元素
- php - PHP/Laravel 只检查一次函数中的条件
- javascript - 返回 null 的对象数组
- javascript - 当数字达到一定范围时,它会回到以前的数字
- image - 在同一个图像张量上使用 torchvision.utils.save_image 两次会使第二次保存不起作用。这是怎么回事?
- sql - SSIS 包失败。“清理失败。为 Web 服务创建的代理可能尚未删除。”