简体   繁体   中英

Swift 4 Decodable parsing json data in array

I have a problem with parsing data from web service, it seems that the decodable protocol couldn't parse this json 数据

This is my parsing data using generics.

public func requestGenericData<T: Decodable>(urlString: String, httpMethod: String?, token: String!, completion: @escaping(T) ->()) {
    let fullStringUrl = url + urlString
    guard let url = URL(string: fullStringUrl) else { return }
    guard let token = token else { return }
    var urlRequest = URLRequest(url: url)
    urlRequest.setValue("application/json", forHTTPHeaderField: "accept")
    urlRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
    urlRequest.httpMethod = httpMethod
    URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
        if self.isInternetAvailable() {
            guard let data = data else { return }
            if let httpResponse = response as? HTTPURLResponse {
                if httpResponse.statusCode >= 200 && httpResponse.statusCode < 300 {
                    do {
                        let obj = try JSONDecoder().decode(T.self, from: data)
                        completion(obj)
                    } catch {
                        print("Error: \(String(describing: error))\n StatusCode: \(httpResponse.statusCode)")
                    }
                }
            }
        } else {
            showAlert(title: "No Internet Connect", message: "Please open your network and try again.", alertStyle: .alert, buttonTitle: "OK", buttonStyle: .default)
            return
        }
    }.resume()
}

This is my model

struct JobWithCategory: Decodable {
   let jobTypeID: Int
   let jobCategoryID: Int
   let name: String
   let getJobs: [getJobs]
}
struct getJobs: Decodable {
   let name: String
   let description: String
}
struct JobCategories: Decodable {
   let jobCategories: [JobWithCategory]
}


apiHelper.requestGenericData(urlString: "url/on/something/else", httpMethod: "GET", token: token) { (jobCategories: [JobCategories]) in
        print(jobCategories)
    }

Now i'm having with this issue on my console printed:

Error: typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array but found a dictionary instead.", underlyingError: nil))

What do I missed or did something wrong with my implementation? Could someone help me out on this one, and so please elaborate why is this happening so I can have a good grasp on whats going on on my code.

Thanks in advance :)

Because you use

[JobCategories]

as the completion T is inferred to array so

 T.self = [JobCategories].self

not a dictionary , so try this

apiHelper.requestGenericData(urlString: "url/on/something/else", 
  httpMethod: "GET", token: token) { (jobCategories:JobCategories) in
    print(jobCategories.jobCategories)
}

Please read the error message

Expected to decode Array but found a dictionary instead

The expected side shows what you are doing (wrong) and the found side shows the actual type.

In terms of Decodable a dictionary is a struct. So it's

...{ (jobCategories: JobCategories) in

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