根据JSON标准RFC 7159 ,这是有效的 json:
22
如何使用 swift4 的可解码将其解码为 Int?这不起作用
let twentyTwo = try? JSONDecoder().decode(Int.self, from: "22".data(using: .utf8)!)
最佳答案
它可以与良好的 JSONSerialization
和 .allowFragments
配合使用
阅读选项。来自 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
}
关于Swift 4 解码简单根级别 json 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52316037/