上下文
我正在与Firebase数据库REST和JSONDecoder / JSONEncoder合作。到目前为止一直运作得很好。然而,对于移除数据,预期返回的响应是null,而JSONDecoder似乎不太喜欢这一点。
这是我通过邮递员发送的查询类型,以及我要返回的内容(不包括敏感数据)。
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:“给定的数据无效的JSON。”,underlyingError:可选(Error Domain=NSCocoaErrorDomain Code=3840 )JSON文本没有以数组或对象开头,并选择允许不设置片段。UserInfo={NSDebugDescription=JSON文本没有以数组或对象开始,并选择允许不设置片段。})
我尝试创建一个自定义类型(NoReply)来按照A以前的职位来处理这个问题,但是没有效果。
代码
这就是错误发生的地方:
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。
有什么建议吗?
请注意,这是他们的文档对删除操作的响应的说明:
一个成功的删除请求由包含JSON
null的200 OK HTTP状态代码指示。
发布于 2018-08-02 22:51:40
不幸的是,JSONDecoder没有公开支持JSON片段(如solo null值)的底层JSONSerialization选项(.allowFragments)。您可以尝试转换响应,或者直接使用JSONSerialization。不幸的是,这里没有什么好做的。
发布于 2018-08-03 15:52:08
快速跟进
经过几次成功的黑客攻击之后,我想出的最优雅的解决方案是:
首先,转换:
if "null" == String(data: data, encoding: .utf8) { let json = Data("{}".utf8)
然后反馈给处理请求响应的闭包:
resource: { let decoder = JSONDecoder() return try decoder.decode(Resource.self, from: $0) },
资源只有以下几个方面:
公共结构NoReply:可解码{}
这现在很好,并且允许我处理删除案例,并在一个不存在的对象上获取它返回null的案例。
谢谢你的帮助!
https://stackoverflow.com/questions/51663004
复制相似问题