简体   繁体   English

Swift 4 Json编码和解码

[英]Swift 4 Json Encoding and Decoding

Here is my code to get complete Json; 这是我获得完整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)

My Json dict is as follows; 我的杰森格言如下:

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

and after decoding of Json, i only need to get this part; 在解码了Json之后,我只需要获得这一部分;

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

i have issue with decoder below, to get value of "Hello"; 我下面的解码器有问题,以获取“ Hello”的值;

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

The actual type of the encoded JSON is [String:[Product]] so decode that and get the value for Hello 编码的JSON的实际类型为[String:[Product]]因此请对其进行解码并获取Hello的值

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

Alternatively create an umbrella Root struct 或者创建一个伞形Root结构

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

and decode that 并解码

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM