Amed LM AB
Amed LM AB

Reputation: 43

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.

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()
    }

Upvotes: 0

Views: 110

Answers (1)

AamirR
AamirR

Reputation: 12198

Your CodingKeys match the property names, so you can get rid of the enum at all

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

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

Above decoder will treat keys such as company_name to be assigned to companyName property of your struct.

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 {
    self.dataSource = try decoder.decode([UserHosting].self, from: data)
} catch {
    print("JSON Decoding Error \(error)")
}

Upvotes: 1

Related Questions