如何在 Swift 中从 JSON 解码大量数字

Max*_*Max 0 parsing json swift codable

我如何像这样解析 JSON:

let json = "{\"key\":18446744073709551616}"

struct Foo: Decodable {
    let key: UInt64
}

let coder = JSONDecoder()
let test = try! coder.decode(Foo.self, from: json.data(using: .utf8)!)
Run Code Online (Sandbox Code Playgroud)

问题是这个数字对于UInt64. 我知道 Swift 中没有更大的整数类型。

Parsed JSON number <18446744073709551616> does not fit in UInt64
Run Code Online (Sandbox Code Playgroud)

我不介意把它作为Stringor Data,但这是不允许的,因为JSONDecoder知道它应该是一个数字:

Expected to decode String but found a number instead.
Run Code Online (Sandbox Code Playgroud)

Mar*_*n R 5

您可以Decimal改用:

let json = "{\"key\":184467440737095516160000001}"

struct Foo: Decodable {
    let key: Decimal
}

let coder = JSONDecoder()
let test = try! coder.decode(Foo.self, from: json.data(using: .utf8)!)
print(test) // Foo(key: 184467440737095516160000001)
Run Code Online (Sandbox Code Playgroud)

Decimal是 Swift 覆盖类型,NSDecimalNumber其中

... 可以表示任何可以表示为的数字,mantissa x 10^exponent其中尾数是最多 38 位的十进制整数,指数是从 –128 到 127 的整数。

Double如果不需要完整精度,您也可以将其解析为:

struct Foo: Decodable {
    let key: Double
}

let coder = JSONDecoder()
let test = try! coder.decode(Foo.self, from: json.data(using: .utf8)!)
print(test) // Foo(key: 1.8446744073709552e+36)
Run Code Online (Sandbox Code Playgroud)