TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: Error fetching JSON data

Forums > SwiftUI

I am getting an error trying to fetch data using Square's customer API.

debugDescription: "No value associated with key CodingKeys(stringValue: \"customer\", intValue: nil) (\"customer\").", underlyingError: nil))

Here is an example of the returned data:

{
  "customers": [
    {
      "id": "MJAG403GV96BX367R56N4FZJTG",
      "created_at": "2021-11-07T04:18:21.42Z",
      "updated_at": "2021-11-07T23:10:20Z",
      "given_name": "Test",
      "family_name": "Customer",
      "email_address": "email@email.com",
      "address": {
        "address_line_1": "123 Any St",
        "locality": "Somewhere",
        "administrative_district_level_1": "CA",
        "postal_code": "55555"
      },
      "phone_number": "+12025551234",
      "preferences": {
        "email_unsubscribed": false
      },
      "creation_source": "DIRECTORY",
      "segment_ids": [
        "MLPYEYRXNK0KW.REACHABLE"
      ],
      "version": 1
    }
  ]
}

And this is what I have for the model currently:

struct arrayOfCustomers: Codable {
    var customer: [Customer]
}

struct Customer: Codable, Identifiable  {
    var id: String
    var created_at: Date
    var updated_at: Date
    var given_name, family_name, email_address, phone_number: String?

    struct address: Codable {
        var address_line_1, locality, administrative_district_level_1, postalCode: String?
        var country: String?
    }
}

3      

I have use "Ducky" (helper for JSON) and got this

import Foundation

struct Square: Decodable {
  struct Customer: Decodable, Identifiable {
    struct Address: Decodable {
      let addressLine1: String
      let locality: String
      let administrativeDistrictLevel1: String
      let postalCode: String
    }

    struct Preference: Decodable {
      let emailUnsubscribed: Bool
    }

    let id: String
    let createdAt: Date
    let updatedAt: Date
    let givenName: String
    let familyName: String
    let emailAddress: String
    let address: Address
    let phoneNumber: String
    let preferences: Preference
    let creationSource: String
    let segmentIds: [String]
    let version: Int
  }

  let customers: [Customer]
}

If you use. You able to use camelCase

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

3      

Post your code that decodes the JSON, that's likely where the problem lies.

3      

Here is the code that decodes the JSON:

class apiCall {
func getCustomers(completion:@escaping (arrayOfCustomers) -> ()) {
    guard let url = URL(string: "https://connect.squareup.com/v2/customers") else {
        print("Could not use URL")
        return
    }

    var request = URLRequest(url: url)
    request.httpMethod = "GET"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.setValue("2021-10-20", forHTTPHeaderField: "Square-Version")
    request.setValue("Bearer (Access Token is in my actual code)", forHTTPHeaderField: "Authorization")

    URLSession.shared.dataTask(with: request) { (data, _, _) in
        let customers = try! JSONDecoder().decode(arrayOfCustomers.self, from: data!)
            print(customers)
        for customer in customers.customer {
            print(customer.given_name)
        }
            DispatchQueue.main.async {
                completion(customers)
            }
    }
    .resume()
}
}

3      

The problem is that you use:

var customer: [Customer]

but the key in the JSON is customers (with an s), not customer.

3      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.