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/52316037/

相关文章:

swift - 如何创建加号栏按钮项

swift - 处理 JSON 分页,并将数据添加到 TableView ?

ios - 可解码类的失败初始化器

swift - 生成错误 : missingLinuxMain

ios - 我如何从 native swift 代码中使用 native RCNAsyncStorage 模块

swift - 为什么通用函数在转换为相同类型时会崩溃?

json - Swift Codable 没有按预期工作?

ios - 如何从api获取图片

swift - 使类可编码

ios - 无法将类型 '[[ModelName]?]' 的值转换为预期的参数类型 '[ModelName].Type'