繁体   English   中英

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

[英]How to decode a large number from JSON in Swift

我如何解析 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)!)

问题是这个数字对于UInt64来说太大了。 我知道 Swift 中没有更大的 integer 类型。

Parsed JSON number <18446744073709551616> does not fit in UInt64

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

Expected to decode String but found a number instead.

您可以改用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)

DecimalNSDecimalNumber的 Swift 覆盖类型

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

如果不需要完整精度,您也可以将其解析为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)

似乎是 JSONDecoder 在幕后使用 NSDecimalNumber

struct Foo: Decodable {
    let key: Int
}

// this is 1 + the mantissa of NSDecimalNumber.maximum
let json = "{\"key\":340282366920938463463374607431768211456}"
let coder = JSONDecoder()
let test = try! coder.decode(Foo.self, from: json.data(using: .utf8)!)

即使在 DecodingError 中,数字也没有准确表示:

Parsed JSON number <340282366920938463463374607431768211450> does not fit in Int.

因此,如果您希望能够以最大精度解码(尽管您仍然可能会默默地失去精度),请使用Decimal 否则,您只需要对向您发送 JSON 的人大喊大叫。


请注意,虽然文档

尾数是十进制 integer 最多 38 位

它实际上是一个 128 位无符号 integer,因此它也可以表示一些 39 位数字,如上所示。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM