根据JSON标准
RFC 7159,这是有效的json:
22
如何使用swift4的可解码将其解码为Int?这不起作用
let twentyTwo = try? JSONDecoder().decode(Int.self,from: "22".data(using: .utf8)!)
它适用于良好的’JSONSerialization和.allowFragments
阅读选项.从 documentation:
原文链接:https://www.f2er.com/swift/319890.html阅读选项.从 documentation:
allowFragments
Specifies that the parser should allow top-level objects that are not an instance of NSArray or NSDictionary.
例:
let json = "22".data(using: .utf8)! if let value = (try? JSONSerialization.jsonObject(with: json,options: .allowFragments)) as? Int { print(value) // 22 }
但是,JSONDecoder没有这样的选项,也不接受顶级
不是数组或字典的对象.人们可以在中看到
source code那个decode()方法调用
JSONSerialization.jsonObject()没有任何选项:
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 }