![](/img/trans.png)
[英]Swift - Convert nested objects into an array of objects using decodable
[英]Using Decodable to decode array of nested objects
幾天前我開始使用 Decodable ,我想知道是否可以創建模型“汽車”而無需創建更多模型,具有以下 JSON:
{
"cars": [
{
"id": 1,
"name": "car1"
},
{
"id": 2,
"name": "car2"
},
{
"id": 3,
"name": "car3"
}
],
"pagination": {
"page": 1,
"offset": 20
}
}
我找到的唯一解決方案是創建一個像“Response”這樣的“wrappwer”模型,其中包含一個 [Cars] 屬性。
有人可以向我確認僅使用“汽車”模型就可以解碼這個 JSON 嗎?
謝謝你。
此致
你可以試試
let str = """
{
"cars": [
{
"id": 1,
"name": "car1"
},
{
"id": 2,
"name": "car2"
},
{
"id": 3,
"name": "car3"
}
],
"pagination": {
"page": 1,
"offset": 20
}
}
"""
do {
let tr = try JSONSerialization.jsonObject(with: Data(str.utf8), options: []) as! [String:Any]
let da = try JSONSerialization.data(withJSONObject: tr["cars"] , options: [])
let res = try JSONDecoder().decode([Car].self, from: da)
print(res)
}
catch {
print(error)
}
struct Car: Codable {
let id: Int
let name: String
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.