我有一个JSON对象,有递增的名字要解析,我想把输出的结果存储到一个有名字字段和宠物字段列表的对象中。我通常使用JSONDecoder,因为它很方便,很容易使用,但我不想硬编码CodingKey,因为我认为这是非常糟糕的做法。
输入。
{"shopName":"KindHeartVet", "pet1":"dog","pet2":"hamster","pet3":"cat", ...... "pet20":"dragon"}
我想把结果存储在的对象里,就像下面这样。
class VetShop: NSObject, Decodable {
var shopName: String?
var petList: [String]?
private enum VetKey: String, CodingKey {
case shopName
case petList
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: VetKey.self)
shopName = try? container.decode(String.self, forKey: .shopName)
// implement storing of petList here.
}
}
我很苦恼的是,由于CodingKey是枚举,它是一个让常量,所以我不能修改(也不应该修改)一个常量,但我需要将petList映射到 "petN "字段,其中N是递增的数字。
EDIT :
我肯定不能改变API响应结构,因为这是一个公共API,不是我开发的东西,我只是想从这个API中解析和获取值,希望这能清除困惑!
Codable
有动态键的规定。如果你绝对不能改变你得到的JSON的结构,你可以为它实现一个像这样的解码器。
struct VetShop: Decodable {
let shopName: String
let pets: [String]
struct VetKeys: 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 {
let container = try decoder.container(keyedBy: VetKeys.self)
var pets = [String]()
var shopName = ""
for key in container.allKeys {
let str = try container.decode(String.self, forKey: key)
if key.stringValue.hasPrefix("pet") {
pets.append(str)
} else {
shopName = str
}
}
self.shopName = shopName
self.pets = pets
}
}
你可以尝试这样来解析你的数据 Dictionary
. 这样,你就可以得到字典的所有键。
let url = URL(string: "YOUR_URL_HERE")
URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in
guard let data = data, error == nil else { return }
do {
let dics = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! Dictionary<String, Any>
let keys = [String](dics.keys)
print(keys) // You have the key list
print(dics[keys[0]]) // this will print the first value
} catch let error as NSError {
print(error)
}
}).resume()
希望你能弄清楚你需要做什么。