Swift 4解码简单的根级json值
发布时间:2020-12-14 05:42:51 所属栏目:百科 来源:网络整理
导读:根据JSON标准 RFC 7159,这是有效的json: 22 如何使用swift4的可解码将其解码为Int?这不起作用 let twentyTwo = try? JSONDecoder().decode(Int.self,from: "22".data(using: .utf8)!) 它适用于良好的’JSONSerialization和.allowFragments 阅读选项.从 doc
根据JSON标准
RFC 7159,这是有效的json:
22 如何使用swift4的可解码将其解码为Int?这不起作用 let twentyTwo = try? JSONDecoder().decode(Int.self,from: "22".data(using: .utf8)!)
它适用于良好的’JSONSerialization和.allowFragments
阅读选项.从 documentation:
例: let json = "22".data(using: .utf8)! if let value = (try? JSONSerialization.jsonObject(with: json,options: .allowFragments)) as? Int { print(value) // 22 } 但是,JSONDecoder没有这样的选项,也不接受顶级 open func decode<T : Decodable>(_ type: T.Type,from data: Data) throws -> T { let topLevel: Any do { topLevel = try JSONSerialization.jsonObject(with: data) } catch { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [],debugDescription: "The given data was not valid JSON.",underlyingError: error)) } // ... return value } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |