我想将以下JSON表示为符合Codable
的结构:
{
"trooper": {"name": "Trooper", "type": "alsatian"},
"spot": {"name": "Spot", "type": "labrador"},
"sniffles": {"name": "Sniffles", "type": "poodle"}
}
列表并不详尽,即列表中可以有任意数量的狗。
{"name": "Sniffles", "type": "poodle"}
部分很简单,可以这样完成:
struct Dog: Codable {
var name: String
var type: String
}
那根级别呢?
答案 0 :(得分:1)
这就是我想要的:
let str = """
{
"trooper": {"name": "Trooper", "type": "alsatian"},
"spot": {"name": "Spot", "type": "labrador"},
"sniffles": {"name": "Sniffles", "type": "poodle"}
}
"""
struct Dog: Codable {
var name: String
var type: String
}
if let data = str.data(using: .utf8) {
do {
let decoder = JSONDecoder()
let dogs = try decoder.decode([String: Dog].self, from: data)
print(dogs)
} catch {
print(error)
}
}