gpt4 book ai didi

Swift 4 解码简单根级别 json 值

转载 作者:行者123 更新时间:2023-11-30 11:09:33 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com