json - 如何在 Swift 中从 JSON 中解码大量数字
问题描述
我如何像这样解析 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 中没有更大的整数类型。
Parsed JSON number <18446744073709551616> does not fit in UInt64
我不介意将它作为String
or Data
,但这是不允许的,因为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)
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)