这是我获取完整 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)
}