简体   繁体   English

快速从JSON创建数组

[英]create an array from JSON in swift

I am trying to convert JSON data into an array but I do not really have any idea how to do it. 我正在尝试将JSON数据转换为数组,但是我真的不知道该怎么做。

I get the data and save it in strings and I can also show it on display. 我获取数据并将其保存为字符串,也可以在显示屏上显示它。

struct User_Hosting: Codable {
    let company_name: String
    let website: String
    let street: String
    let housenumber: String
    let zip: String
    let city: String    

    enum CodingKeys: String, CodingKey {
        case company_name = "company_name"
        case website = "website"
        case street = "street"
        case housenumber = "housenumber"
        case zip = "zip"
        case city = "city"
    }
}

And here some other codes: 还有其他一些代码:

let url = URL(string: "myURL.com")

        URLSession.shared.dataTask(with: url!, completionHandler: { [weak self] (data, response, error) in
            guard let data = data, error == nil else {
                print(error?.localizedDescription ?? "An error occurred")
                return
            }
            DispatchQueue.main.async {
                self?.dataSource = try! JSONDecoder().decode([User_Hosting].self, from: data)
            }
        }).resume()
    }

Your CodingKeys match the property names, so you can get rid of the enum at all 您的CodingKeys与属性名称匹配,因此您完全可以摆脱enum

struct UserHosting: Codable {
    let companyName: String
    let website: String
    let street: String
    let housenumber: String
    let zip: String
    let city: String    
}

Since you have a some snake case keys in JSON, you can change the JSONDecoder.keyDecodingStrategy to convertFromSnakeCase , like so 由于JSON中有一些蛇格键,因此您可以将JSONDecoder.keyDecodingStrategy更改为convertFromSnakeCase ,如下所示

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase

Above decoder will treat keys such as company_name to be assigned to companyName property of your struct. 上面的解码器将把诸如company_name键分配给您的结构的companyName属性。

Finally you can decode your JSON in a do-catch block, so in case of an error we will have a message as to what went wrong. 最后,您可以在do-catch块中对JSON进行解码,因此,如果发生错误,我们将收到一条有关错误原因的消息。

do {
    self.dataSource = try decoder.decode([UserHosting].self, from: data)
} catch {
    print("JSON Decoding Error \(error)")
}

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

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