Swift 4:解码数组

Séb*_*EMY 1 arrays json decode swift

我想轻松地从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)


            return jsonCatalogs

        } catch {
            print ("error")
            return nil
        }
Run Code Online (Sandbox Code Playgroud)

我不知道为什么它在Xcode 9的Swift 4中不起作用。谢谢您的帮助;-)

Er.*_*tri 5

实际上,你的结构是错误的,

    fileprivate struct Catalog: Codable {
        var name: String
        var order: Int
        var products: [Products] // this key is wrong in your question, it should be products instead of product
    }

    //this particular structure was missing as your products is having a dictionary and in that dictionary you are having product at key product
    fileprivate struct Products: Codable {
        var product: Product
    }
    fileprivate struct Product: Codable {
        var title: String
        var reference: String
    }
Run Code Online (Sandbox Code Playgroud)

现在您可以检查功能,也可以使用try catch和错误处理功能轻松调试它

...

// JSON解码器

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

        let jsonDecoder = JSONDecoder()

        let jsonCatalogs = try? jsonDecoder.decode(Array<Catalog>.self,from: jsonData)
        print(jsonCatalogs)
        return jsonCatalogs

    } catch let error {
        print ("error -> \(error)") // this will always give you the exact reason for which you are getting error
        return nil
    }
Run Code Online (Sandbox Code Playgroud)