小编Séb*_*EMY的帖子

Swift 4:解码数组

我想轻松地从Xcode 9上的Swift 4用Decode协议解码JSON文件。这是我的问题:如何像这样解码JSON:

[
  {
    "name": "My first Catalog",
    "order": 0,
    "products": [
      {
        "product": {
          "title": "product title",
          "reference": "ref"
        }
      }
    ]
  }
]
Run Code Online (Sandbox Code Playgroud)

我尝试了这个,但是没有用

fileprivate struct Catalog: Codable {
    var name: String
    var order: Int
    var product: [Product]
}

fileprivate struct Product: Codable {
    var title: String
    var reference: String
}

...

// JSON Decoder
        do {
            let jsonData = try Data(contentsOf: URL(fileURLWithPath: filePath), options: .alwaysMapped)

            let jsonDecoder = JSONDecoder()

            let jsonCatalogs = try? jsonDecoder.decode(Array<Catalog>.self,
                                                       from: jsonData) …
Run Code Online (Sandbox Code Playgroud)

arrays json decode swift

1
推荐指数
1
解决办法
2892
查看次数

标签 统计

arrays ×1

decode ×1

json ×1

swift ×1