Swift 4 decode simple root level json value

喜欢而已 提交于 2019-11-27 06:44:41

问题


According to the JSON standard RFC 7159, this is valid json:

22

How do I decode this into an Int using swift4's decodable? This does not work

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

回答1:


It works with good ol' JSONSerialization and the .allowFragments reading option. From the documentation:

allowFragments

Specifies that the parser should allow top-level objects that are not an instance of NSArray or NSDictionary.

Example:

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

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

However, JSONDecoder has no such option and does not accept top-level objects which are not arrays or dictionaries. One can see in the source code that the decode() method calls JSONSerialization.jsonObject() without any option:

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
}


来源:https://stackoverflow.com/questions/46768535/swift-4-decode-simple-root-level-json-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!