0

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

1 回答 1

2

编码 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)
于 2017-11-04T12:03:22.283 回答