gpt4 book ai didi

json - 使用通配符键解析 JSON

转载 作者:搜寻专家 更新时间:2023-11-01 06:11:44 25 4
gpt4 key购买 nike

我正在解析一个设计不佳的 JSON 结构,我可以在其中找到被重用为指向更多数据的键的值。像这样

 {"modificationDate" : "..."
"type" : "...",
"version" : 2,
"manufacturer": "<WILDCARD-ID>"

"<WILDCARD-ID>": { /* known structure */ } }

WILDCARD-ID 在运行时几乎可以是任何东西,所以我无法在编译时将它映射到结构中某处的字段。但是一旦我取消引用该字段,它的值就具有已知结构,此时我可以按照通常的过程将 JSON 映射到 struct

我发现自己正在走这条路

let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any]
let manDict = json["manufacturer"]
let data = NSKeyedArchiver.archivedData(withRootObject: manDict)
// now you have data!

但这看起来很迂回,这让我觉得也许有更简洁的方法来完成这个?

最佳答案

您可以将自定义键与 Decodable 一起使用,如下所示:

let json = """
{
"modificationDate" : "...",
"type" : "...",
"version" : 2,
"manufacturer": "<WILDCARD-ID>",
"<WILDCARD-ID>": {
"foo": 1
}
}
""".data(using: .utf8)!

struct InnerStruct: Decodable { // just as an example
let foo: Int
}

struct Example: Decodable {
let modificationDate: String
let type: String
let version: Int
let manufacturer: String
let innerData: [String: InnerStruct]

enum CodingKeys: String, CodingKey {
case modificationDate, type, version, manufacturer
}

struct CustomKey: CodingKey {
var stringValue: String
var intValue: Int?
init?(stringValue: String) {
self.stringValue = stringValue
}
init?(intValue: Int) {
self.stringValue = "\(intValue)";
self.intValue = intValue
}
}

init(from decoder: Decoder) throws {
// extract all known properties
let container = try decoder.container(keyedBy: CodingKeys.self)
self.modificationDate = try container.decode(String.self, forKey: .modificationDate)
self.type = try container.decode(String.self, forKey: .type)
self.version = try container.decode(Int.self, forKey: .version)
self.manufacturer = try container.decode(String.self, forKey: .manufacturer)

// get the inner structs with the unknown key(s)
var inner = [String: InnerStruct]()
let customContainer = try decoder.container(keyedBy: CustomKey.self)
for key in customContainer.allKeys {
if let innerValue = try? customContainer.decode(InnerStruct.self, forKey: key) {
inner[key.stringValue] = innerValue
}
}

self.innerData = inner
}
}

do {
let example = try JSONDecoder().decode(Example.self, from: json)
print(example)
}

关于json - 使用通配符键解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54947139/

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