Swift 4 解码简单根级别 json 值
Swift 4 decode simple root level json value
根据JSON标准RFC 7159,这是有效的json:
22
如何使用 swift4 的 decodable 将其解码为 Int?这不起作用
let twentyTwo = try? JSONDecoder().decode(Int.self, from: "22".data(using: .utf8)!)
它适用于很好的 ol' 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
}
在 iOS 13.1+ 和 macOS 10.15.1+ 中 JSONDecoder
可以在根级别处理 原始 类型。
在马丁回答下方的链接文章中查看最新评论(2019 年 10 月)。
根据JSON标准RFC 7159,这是有效的json:
22
如何使用 swift4 的 decodable 将其解码为 Int?这不起作用
let twentyTwo = try? JSONDecoder().decode(Int.self, from: "22".data(using: .utf8)!)
它适用于很好的 ol' 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
}
在 iOS 13.1+ 和 macOS 10.15.1+ 中 JSONDecoder
可以在根级别处理 原始 类型。
在马丁回答下方的链接文章中查看最新评论(2019 年 10 月)。