使用 Xcode 10.2 和 iOS 12.x,我们能够从 json 字符串中提取 Decimal。使用 Xcode 11.1 和 iOS 13.1 会引发异常
预期解码 Double,但发现了字符串/数据。
class MyClass : Codable {
var decimal: Decimal?
}
Run Code Online (Sandbox Code Playgroud)
然后尝试解析它
let json = "{\"decimal\":\"0.007\"}"
let data = json.data(using: .utf8)
let decoder = JSONDecoder()
decoder.nonConformingFloatDecodingStrategy = .convertFromString(positiveInfinity: "s1", negativeInfinity: "s2", nan: "s3")
do {
let t = try decoder.decode(MyClass.self, from: data!)
} catch {
print(error)
}
Run Code Online (Sandbox Code Playgroud)
如果我将 json 字符串更改为
let json = "{\"decimal\":0.007}"
它有效,但我们又失去了精度。有任何想法吗?