gpt4 book ai didi

json - json 的 Swift json 动态 key 解析

转载 作者:行者123 更新时间:2023-12-05 02:01:52 25 4
gpt4 key购买 nike

我有 json 响应,其中只有一个键名更改其余部分是相同的,并且想在不重复相同结构的情况下进行解析。

"attributes": {
"symbol":"EUR",
"name":"Euro",
"precision":2,
}

"attributes":{
"symbol":"EUR",
"name":"Euro",
"precision_for_fiat_price":2,
}

如何在json解析中动态处理这个precision key

最佳答案

您可以使用自定义 keyDecodingStrategy

本质上,您编写了一些逻辑来检查当前编码键路径是否符合某些条件,如果符合,则将该键映射到 precision 键。

例如:

struct Root : Codable {
let attributes: Attributes
}

struct Attributes : Codable {
let symbol: String
let name: String
let precision: Int

enum CodingKeys: CodingKey {
case symbol
case name
case precision
}
}

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .custom({
keys in

// This will decode every precision_for_fiat_price key in the json as "precision".
// You might not want this.
// Make this criteria stricter if you need to. An example is shown below
if keys.last?.stringValue == "precision_for_fiat_price" {
return Attributes.CodingKeys.precision
}

// this will only decode those precision_for_fiat_price that have "attribute" as their parent as "precision"
// if stringPath.suffix(2) == ["attributes", "precision_for_fiat_price"] {
// return Attributes.CodingKeys.precision
// }
return keys.last!
})
let json = """
{
"attributes":{
"symbol":"EUR",
"name":"Euro",
"precision_for_fiat_price":2

}
}
""".data(using: .utf8)!
let decoded = try decoder.decode(Root.self, from: json)

关于json - json 的 Swift json 动态 key 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66218058/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com