Swift Codable,数组值作为键
Posted
技术标签:
【中文标题】Swift Codable,数组值作为键【英文标题】:Swift Codable, array value as key 【发布时间】:2018-11-05 20:31:17 【问题描述】:这是我的 JSON:
"items": [
"name": "Item 1",
"description": "This is Item 1",
"categories": ["Category1", "Category2", "Category3", "Category4"],
"size": ["M", "L"]
,
"name": "Item 2",
"description": "This is Item 2",
"categories": ["Category1", "Category3", "Category4"],
"size": ["M"]
]
我可以很好地阅读和打印它
但是,我想将此结构更改为这样的结构,其中每个项目按类别和大小分隔,并且类别用作键。
"categories":
"category1": [
"name": "Item 1",
"description": "This is Item 1",
"size": "M"
,
"name": "Item 1",
"description": "This is Item 1",
"size": "L"
,
"name": "Item 2",
"description": "This is Item 2",
"size": "M"
...],
"category2": [
...
]
我已经创建了以下数据结构,但我不太确定如何继续:
struct Categories: Codable
let category: String
let items: [Item]
struct Item: Codable
let name, description, size: String
Codable 是解决这个问题的正确方法吗?如果是这样的话;我将如何继续实现这一目标?
【问题讨论】:
为什么要更改 JSON 以包含这么多重复数据? 【参考方案1】:对于你当前需要的 json
struct Root: Codable
let categories: [String:[Item]]
struct Item: Codable
let name, description, size: String
不过我觉得还是这样比较好
"category1": [
"name": "Item 1",
"description": "This is Item 1",
"size": "M"
,
"name": "Item 1",
"description": "This is Item 1",
"size": "L"
,
"name": "Item 2",
"description": "This is Item 2",
"size": "M"
],
"category2": [
]
这会让你这样做
let res = try? JSONDecoder().decode([String:[Item]].self,from:jsonData)
没有Root
结构和无用的categories
键
【讨论】:
以上是关于Swift Codable,数组值作为键的主要内容,如果未能解决你的问题,请参考以下文章
使用 Swift 4 中的 JSONDecoder,缺少的键可以使用默认值而不是可选属性吗?