简体   繁体   English

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

[英]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 我从网络服务解析数据时遇到问题,似乎可解码协议无法解析此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)) 错误:typeMismatch(Swift.Array,Swift.DecodingError.Context(codingPath:[],debugDescription:“预计要解码Array,但找到了字典。”,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被推断为数组,所以

 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 预期对Array进行解码,但是找到了一个字典

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. Decodable而言,字典是一种结构。 So it's 所以是

...{ (jobCategories: JobCategories) in

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM