根据JSON标准RFC 7159,这是有效的json:
22
我如何使用swift4的可解码代码将其解码为Int?这不起作用
let twentyTwo = try? JSONDecoder().decode(Int.self, from: "22".data(using: .utf8)!)
[它与JSONSerialization
和.allowFragments
都很好阅读选项。从documentation:
allowFragments
指定解析器应允许不是NSArray或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
}
在iOS 13.1+和macOS 10.15.1+中,JSONDecoder
可以处理根级别的primitive类型。
[在马丁的回答下面的链接文章中查看最新评论(2019年10月)。