从JSON解析为字符串的十进制 [英] Parsing Decimal from JSON presented as string

查看:169
本文介绍了从JSON解析为字符串的十进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Xcode 10.2和iOS 12.x,我们能够从json字符串中提取Decimal。在Xcode 11.1和iOS 13.1中,它会引发异常

With Xcode 10.2 and iOS 12.x we were able to extract Decimal from json string. With Xcode 11.1 and iOS 13.1 it is throwing exception


希望对Double进行解码,但是找到了一个字符串/数据。

Expected to decode Double but found a string/data instead.



class MyClass : Codable {

     var decimal: Decimal?
 }

然后尝试解析它

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)
 }

如果我将json字符串更改为

If I change json string as

let json = {\ decimal\:0.007}

它可以工作,但随后我们又失去了精度。

It works, but then again we are losing precision. Any ideas?

推荐答案

struct Root: Codable {
    let decimal: Decimal
}







extension Root {
    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        decimal = try Decimal(string: container.decode(String.self, forKey: .decimal)) ?? .zero
    }
}







let json = #"{"decimal":"0.007"}"# 
do {
    let root = try JSONDecoder().decode(Root.self, from: .init(json.utf8))
    print(root)
} catch {
    print(error)
}

这将打印


Root(decimal:0.007)

Root(decimal: 0.007)

这篇关于从JSON解析为字符串的十进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆