我在解码 json 时遇到问题。我已经学习了很多教程,但没有使用复杂的 json 结构。为简单起见,我将代码最小化并使用 Dog 作为示例。
在以下 json 中,我主要只对 Dog 结构感兴趣。json“数据”属性包含随机狗名。所以我不能使用编码键,因为我不知道属性名称。
{
"Response": "success"
"BaseLinkUrl": "https://wwww.example.com",
"Data": {
"Max": {
"name": "Max",
"breed": "Labrador"
},
"Rocky": {
"name": "Rocky",
"breed": "Labrador"
},
...
}
}
我有以下结构:
struct DogResponse : Decodable {
let data : DogResponseData
enum CodingKeys: String, CodingKey {
case data = "Data"
}
}
struct DogResponseData: Decodable {
let dog: Dog //this is a random variable name
enum CodingKeys: String, CodingKey {
case dog = "??random_variable_dog_name??"
}
}
struct Dog: Decodable {
let name: String
let type: String
enum CodingKeys: String, CodingKey {
case name
case type = "breed"
}
}
收集 Dog 结构:
let dogResponse = try JSONDecoder().decode(DogResponse.self, from: data)
print(dogResponse)
我需要在我的“DogResponseData”结构中做什么才能快速识别包含我的 Dog 结构的随机变量?