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