Swift 4 Json 编码和解码

Swift 4 Json Encoding and Decoding

这是我完成的代码Json;

var str = "Hello"
var dictionary = ["key1":"val1", "key2":"val2", "key3":"val3"]

var products = [Product]()

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

func createProducts(title: String, refer: String) {
    products.append(Product(title: title, reference: refer))
}

for element in dictionary {
    createProducts(title: element.key, refer: element.value)
}

var general = [str: products]

let encodedData = try? JSONEncoder().encode(general)
let json = String(data: encodedData!, encoding: .utf8)!
print(json)

我的Json字典如下;

{"Hello":[{"title":"key2","reference":"val2"},{"title":"key3","reference":"val3"},{"title":"key1","reference":"val1"}]}

解码Json后,我只需要得到这部分;

[{"title":"key2","reference":"val2"},{"title":"key3","reference":"val3"},{"title":"key1","reference":"val1"}]

我对下面的解码器有疑问,要获取 "Hello" 的值;

if let decodedData = try! JSONDecoder().decode(general.self, from: json.data(using: .utf8)!) {
    print(decodedData)
}

编码的 JSON 的实际类型是 [String:[Product]] 所以对其进行解码并获得 Hello

的值
do {
    let decodedData = try JSONDecoder().decode([String:[Product]].self, from: Data(json.utf8))
    print(decodedData["Hello"]!)
} catch {
    print(error)
}

或者创建一个伞Root结构

struct Root : Decodable {
    private enum CodingKeys : String, CodingKey { case hello = "Hello" }
    let hello : [Product]
}

并解码

do {
   let decodedData = try JSONDecoder().decode(Root.self, from: Data(json.utf8))
   print(decodedData.hello)