juh*_*aja 3 swift codable ios13
使用 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}"
它有效,但我们又失去了精度。有任何想法吗?
您需要扩展 KeyedDecodingContainer 并添加 Decimal.Type 的实现。
extension KeyedDecodingContainer {
func decode(_ type: Decimal.Type, forKey key: K) throws -> Decimal {
let stringValue = try decode(String.self, forKey: key)
guard let decimalValue = Decimal(string: stringValue) else {
let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value")
throw DecodingError.typeMismatch(type, context)
}
return decimalValue
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个例子:
let json = """
{
"capAmount": "123.45"
}
"""
struct Status: Decodable {
let capAmount: Decimal
enum CodingKeys: String, CodingKey {
case capAmount
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
capAmount = try container.decode(Decimal.self, forKey: .capAmount)
}
}
// Execute it
if let data = json.data(using: .utf8){
let status = try JSONDecoder().decode(Status.self, from: data)
print(status.capAmount)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2668 次 |
| 最近记录: |