Swift 4解码简单的根级别json值

问题描述 投票:10回答:2

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

22

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

let twentyTwo = try? JSONDecoder().decode(Int.self, from: "22".data(using: .utf8)!)
swift swift4 codable
2个回答
12
投票

[它与JSONSerialization.allowFragments都很好阅读选项。从documentation

allowFragments

指定解析器应允许不是NSArray或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
}

0
投票

在iOS 13.1+和macOS 10.15.1+中,JSONDecoder可以处理根级别的primitive类型。

[在马丁的回答下面的链接文章中查看最新评论(2019年10月)。

© www.soinside.com 2019 - 2024. All rights reserved.