Swift 4 解码简单的根级 json 值

标签 swift swift4 codable

根据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/47941826/

相关文章:

ios - Objective C/Swift 如何打开 base64 url​​?

Swift UIBarButtonItem 按下时缺少图像

json - 使用可编码解析 JSON 并忽略 JSON 的第一层

ios - 如何在 Swift Struct 中存储多个回溯日期?

ios - UILongPressGestureRecognizer 访问被点击的按钮

ios - 为什么 UIDocumentMenuViewController 不接受 kUTTypeText?

string - 交换字符串大小写 - swift

ios - 如何从 viewDidLoad 调用 "didUpdateLocation"方法?

ios - '*** -[__NSSingleObjectArrayI objectAtIndex :]: index 1 beyond bounds [0 . 。 0]'

swift - 如何使用 Swift 的 Codable 编码成字典?