【问题标题】:Swift Codable, array value as keySwift Codable,数组值作为键
【发布时间】: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 以包含这么多重复数据?

标签: json swift codable


【解决方案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 键

【讨论】:

    猜你喜欢
    • 2020-02-04
    • 1970-01-01
    • 2018-07-09
    • 2021-05-24
    • 2023-03-07
    • 2018-11-15
    • 1970-01-01
    • 2018-10-27
    相关资源
    最近更新 更多