Swift 4 Decodable解析数组中的json数据

时间:2018-07-26 11:52:41

标签: ios swift decodable

我在解析来自Web服务的数据时遇到问题,似乎可解码协议无法解析此json data

这是我使用泛型解析的数据。

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()
}

这是我的模特

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)
    }

现在我在控制台上遇到了这个问题:

  

错误:typeMismatch(Swift.Array,Swift.DecodingError.Context(codingPath:[],debugDescription:“预期对Array进行解码,但找到了一个字典。”,底层错误:无))

我的实现遗漏了什么或做错了什么?有人可以帮我解决这个问题,所以请详细说明为什么会这样,以便我可以很好地掌握代码中发生的事情。

预先感谢:)

2 个答案:

答案 0 :(得分:0)

因为您使用

[JobCategories]

因为补全T推断为数组,所以

 T.self = [JobCategories].self

不是字典,请尝试

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

答案 1 :(得分:0)

请阅读错误消息

  

打算对Array进行解码,但是找到了一个字典

期望侧显示您的操作(错误),找到侧显示实际的类型。

Decodable而言,字典是一个结构。所以是

...{ (jobCategories: JobCategories) in