Swift Codable,数组值作为键

时间:2018-11-05 20:31:17

标签: json swift codable

这是我的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是否适合此解决方案?如果是这样的话;我将如何实现这一目标?

1 个答案:

答案 0 :(得分: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