Swift 4解码简单的根级json值

mik*_*lam 10 swift swift4 codable

根据JSON标准RFC 7159,这是有效的json:

22
Run Code Online (Sandbox Code Playgroud)

如何使用swift4的可解码将其解码为Int?这不起作用

let twentyTwo = try? JSONDecoder().decode(Int.self, from: "22".data(using: .utf8)!)
Run Code Online (Sandbox Code Playgroud)

Mar*_*n R 12

它适用于良好的ol' JSONSerialization.allowFragments 阅读选项.从文档:

allowFragments

指定解析器应允许不是NSArray或NSDictionary实例的顶级对象.

例:

let json = "22".data(using: .utf8)!

if let value = (try? JSONSerialization.jsonObject(with: json, options: .allowFragments)) as? Int {
    print(value) // 22
}
Run Code Online (Sandbox Code Playgroud)

但是,JSONDecoder没有这样的选项,也不接受不是数组或字典的顶级对象.可以在 源代码中看到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
}
Run Code Online (Sandbox Code Playgroud)

  • 您可以尝试在Apple处提交错误报告. (2认同)

vad*_*ian 5

在 iOS 13.1+ 和 macOS 10.15.1+ 中JSONDecoder可以在根级别处理原始类型。

请参阅 Martin 答案下方的链接文章中的最新评论(2019 年 10 月)。