1

My API returns the following JSON (an array of [CustomClass]):

[{
        "name": "Name A",
        "startingDate": "2018-01-01",
        "duration": 4
    },
    {
        "name": "Name B",
        "startingDate": "2018-01-01",
        "duration": 4
    }
]

I'm using Alamofire to make the request and then parsing the JSON:

static func test(parametersGet:Parameters, completion: @escaping ([CustomStruct]?, Error?) -> Void ) {
        Alamofire.request(API.test, parameters: parametersGet).validate().responseJSON { response in
            switch response.result {
            case .success:
                if let json = response.result.value {
                    let workoutCards = json as! [CustomStruct]
                    completion(workoutCards, nil)
                }
            case .failure(let error):
                completion(nil, error)
            }
        }
    }

CustomStruct it's simply a Codable struct with those keys.

I get the following error: "Could not cast value of type '__NSDictionaryI' to 'Project.CustomStruct'". How can I parse the JSON?

1

2 Answers 2

3

In Your case you will need to decode your jsonData to [CustomStruct] using JSONDecoder

  Alamofire.request(API.test, parameters: parametersGet).validate().responseJSON { response in
            switch response.result {
            case .success:
                if let jsonData = response.data {
                    let jsonDecoder = JSONDecoder()
                    do {
                        let workoutCards = try jsonDecoder.decode([CustomStruct].self, from: jsonData)
                        completion(workoutCards, nil)
                    }catch let error{
                        print(error.localizedDescription)
                        completion(nil, error)
                    }
                }
            case .failure(let error):
                completion(nil, error)
            }
        }
Sign up to request clarification or add additional context in comments.

Comments

0

You can build a struct like so:

    struct Item {
        var name: String
        var startingDate: String
        var duration: String
    }

Then parse the data from the result:

                let jsonDecoder = JSONDecoder()
                do {
                    let workoutCards = try jsonDecoder.decode([Item].self, from: data)
                    completion(workoutCards, nil)
                }catch let error{
                    print(error.localizedDescription)
                    completion(nil, error)
                }
            }
        case .failure(let error):
            completion(nil, error)
        }

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.