2

I'm getting the following error when trying to decode JSON. What's odd is I've used similar code on other endpoints and no issue using UUID.

error:

keyNotFound(CodingKeys(stringValue: "id", intValue: nil), Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: "id", intValue: nil) ("id").", underlyingError: nil))

Here's my class

class Api: ObservableObject {
@State private var showingAlert = false

// completion handler for JSON Data
func getUserData(url: String, completion : @escaping ([RunClubsv2])->()){

    let session = URLSession(configuration: .default)

    session.dataTask(with: URL(string: url)!) { (data, _, err) in

        if err != nil{

            print(err!.localizedDescription)
            return
        }
        //decoding JSON

        do {

            let users = try JSONDecoder().decode([RunClubsv2].self, from: data!)
            print(users)
            //returning data
            completion(users)

        }
        catch{
            print(error)
        }
    }
.resume()
}

Here's my UI code


    @State var runclubv2: [RunClubsv2] = []

    var body: some View {
        VStack {
            if runclubv2.isEmpty{
                Text("damn it")
            }
            else {

                //display data
                List(runclubv2) { runclubv2 in
                    Text(runclubv2.name)
                }

            }

        }
        .onAppear{
            Api().getUserData(url: "<URL EndPoint>") { ([RunClubsv2]) in
                self.runclubv2 = self.runclubv2
            }
        }
    }
}

Here's the response data

[
    {
        "name": "Joggers for Lagers",
        "location": "Amor Artis Brewery, Fort Mill",
        "date": "6:30 PM",
        "category": "Monday"
    },
    {
        "name": "Old Armor Run Club",
        "location": "Kannapolis",
        "date": "6:00 PM",
        "category": "Monday"
    }
]
Robert
  • 809
  • 3
  • 10
  • 19

2 Answers2

2

Please read the JSON carefully. Where is the key id? That’s exactly what the error message says.

I guess your struct conforms to Identifiable with a hard-coded UUID. If so you have to add CodingKeys to exclude id from being decoded.

vadian
  • 274,689
  • 30
  • 353
  • 361
  • I don't understand. I have a similar API call with a similar `struct` and I don't get this error and I don't have an `id` included. – Robert Sep 08 '20 at 20:17
  • The error is clear. The decoder tries to decode a key `id` which obviously doesn’t exist in the JSON. Therefore you have to add `CodingKeys`... – vadian Sep 08 '20 at 20:25
  • Yeah I can read :). What I don't understand is how I can have two similar functions with similar struct's and one works and one doesn't. – Robert Sep 08 '20 at 20:32
  • 1
    Similar is not equal – vadian Sep 08 '20 at 20:35
0

I believe the id needs to be optional. So what happened in your code was that the JSON_VALUE was trying to write into the id key which obviously from what you show us is that there's no key named id.

I assumed that you might also face this following error:

Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "id", intValue: nil), Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "data", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: \"id\", intValue: nil) (\"id\").", underlyingError: nil))

The error is very straightforward No value associated with key CodingKeys(stringValue: \"id\", intValue: nil) (\"id\").

This can be solved.

Your current code must be:

struct RunClubsv2 {
    public var name :String
    public var location :String
    public var date :String
    public var category :String

}

The problem is from this line here public var name :String, which can avoid the error by adding a ? after the String or String?. Which means you are making that optional or nullable.

Lastly, your updated code should be something like this:

struct RunClubsv2 {
    public var name :String?
    public var location :String
    public var date :String
    public var category :String

}
钟智强
  • 459
  • 6
  • 17