加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift 4解码简单的根级json值

发布时间:2020-12-14 05:42:51 所属栏目:百科 来源:网络整理
导读:根据JSON标准 RFC 7159,这是有效的json: 22 如何使用swift4的可解码将其解码为Int?这不起作用 let twentyTwo = try? JSONDecoder().decode(Int.self,from: "22".data(using: .utf8)!) 它适用于良好的’JSONSerialization和.allowFragments 阅读选项.从 doc
根据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
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读