简体   繁体   中英

Parsing JSON in Swift with nil values

I'm using Swift 5 and Xcode 11. I am attempting to parse the JSON coming back from this website, an API I am designing. http://aarontcraig-001-site1.htempurl.com/api/values

The JSON returned from that API call is this:

[
    {
        "Businesses": [],
        "Customer": null,
        "ID": 1,
        "Name": "Coffee Shop",
        "CustomerID": null
    },
...
]

It continues an array. Some of the entries are null, others are not. However, when I parse it, they all come back nil.

Here is my code:

let url = "http://aarontcraig-001-site1.htempurl.com/api/values"
        guard let finalURL = URL(string: url) else {
            return
        }

        URLSession.shared.dataTask(with: finalURL) { (data, response, error) in
            guard let data = data else {return}

            do {
                let myData = try JSONDecoder().decode([Value].self, from: data)

                print(myData)
            }
            catch {
                print("Error parsing \(error)")
            }

and the struct I am using to catch it all:

struct Value: Codable {
    let businesses : [String]?
    let customer : String?
    let iD : Int?
    let name : String?
    let customerID : String?
}

All I get back is nil values, even though clearly many of them aren't. This is what it returns.

[Sunrise.Value(businesses: nil, customer: nil, iD: nil, name: nil, customerID: nil), Sunrise.Value(businesses: nil, customer: nil, iD: nil, name: nil, customerID: nil), Sunrise.Value(businesses: nil, customer: nil, iD: nil, name: nil, customerID: nil), Sunrise.Value(businesses: nil, customer: nil, iD: nil, name: nil, customerID: nil), Sunrise.Value(businesses: nil, customer: nil, iD: nil, name: nil, customerID: nil), Sunrise.Value(businesses: nil, customer: nil, iD: nil, name: nil, customerID: nil)]

What am I doing wrong? Even if I attempt to just capture name which has a value for each entry, it sets it to nil. I am receiving the data, because if I put a breakpoint at data I can see it there.

Map the property names from the JSON to your struct's members using CodingKeys :

struct Value: Codable {
    let businesses: [String]?
    let customer: String?
    let id: Int
    let name: String
    let customerID: String?

    enum CodingKeys: String, CodingKey {
        case businesses = "Businesses"
        case customer = "Customer"
        case id = "ID"
        case name = "Name"
        case customerID = "CustomerID"
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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