【发布时间】:2021-08-07 06:06:09
【问题描述】:
这是我的 JSON
{
"myItems": {
"item1name": [{
"url": "google.com",
"isMobile": true,
"webIdString": "572392"
}, {
"url": "hulu.com",
"isMobile": false,
"webIdString": "sad1228"
}],
"item2name": [{
"url": "apple.com",
"isMobile": true,
"webIdString": "dsy38ds"
}, {
"url": "Facebook.com",
"isMobile": true,
"webIdString": "326dsigd1"
}, {
"url": "YouTube.com",
"isMobile": true,
"webIdString": "sd3dsg4k"
}]
}
}
json可以有多个item(比如item1name, item2name, item3name,...),每个item可以有多个object(例子中第一个item有2个object,第二个item有3个object)。
这是我想要保存到的结构(不完整):
struct ServerResponse: Decodable {
let items: [MyItem]?
}
struct MyItem: Decodable {
let itemName: String?
let url: String?
let isMobile: Bool?
let webIdString: String?
}
在上面的例子中,这意味着items 列表应该有五个MyItem 对象。例如,这些将是 MyItem 对象:
#1: itemName: item1name, 网址:google.com, isMobile:是的, webIdString: 572392
#2: itemName: item1name, 网址:hulu.com, isMobile:假, webIdString: 悲伤1228
#3: itemName: item2name, 网址:apple.com, isMobile:是的, webIdString: dsy38ds
#4: itemName: item2name, 网址:Facebook.com, isMobile:是的, webIdString: 326dsigd1
#5: itemName: item2name, 网址:YouTube.com, isMobile:是的, webIdString: sd3dsg4k
使用 Decodable 对我来说最好的方法是什么?任何帮助,将不胜感激。我想这可能和这个问题类似:How to decode a nested JSON struct with Swift Decodable protocol?
【问题讨论】:
标签: json swift nested decodable