0

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.

2

1 Answer 1

2

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"
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.