Swift.DecodingError.Context - PullRequest
       8

Swift.DecodingError.Context

0 голосов
/ 03 февраля 2020

Я декодирую JSON (Декодер) строку из ответа URL следующим образом и получаю в процессе декодирования следующие сообщения об ошибках:

Ошибка:

typeMismatch ( Swift.String, Swift.DecodingError.Context (codingPath: [_JSONKey (stringValue: «Index 0», intValue: 0), CodingKeys (stringValue: «tags», intValue: nil), _JSONKey (stringValue: «Index 0», intValue : 0)], debugDescription: «Предполагается, что декодируется строка, но вместо этого найдено число.» 1012 *

class func path_getPosts(per_page:Int) -> URL {
        let s = APIwp.base + APIwp.posts + APIwp.per_page + "\(per_page)"
        print(s)
            return URL(string: s)!

        }


    static func getPosts(for per_page: Int, completion: @escaping ([Wordpress], Error?) -> Void) {
        taskGetPosts(url: path_getPosts(per_page: per_page), responseType: [Wordpress].self) { (response, error) in
                if let response = response {
                    completion(response, nil)
                } else {
                    completion([], error)
                }
            }
        }

    @discardableResult static func taskGetPosts<ResponseType: Decodable>(url: URL, responseType: ResponseType.Type, completion: @escaping (ResponseType?, Error?) -> Void) -> URLSessionDataTask {
        let task = URLSession.shared.dataTask(with: url) { (data, response, error)
            in
            guard let data = data else {
                DispatchQueue.main.async {
                    completion(nil, error)
                }
            return
            }

            let decoder = JSONDecoder()
            do {
                let responseObject = try decoder.decode(ResponseType.self, from: data)
                DispatchQueue.main.async { completion(responseObject, nil) }
            } catch let jsonErr {
                print("Error:=: \(jsonErr)")
                DispatchQueue.main.async { completion(nil, error) }
            }
        }
        task.resume()
        return task
    }

1 Ответ

3 голосов
/ 03 февраля 2020

Пожалуйста, , внимательно прочитайте сообщение об ошибке.

Сообщается, что первый элемент (_JSONKey(stringValue: "Index 0", intValue: 0)) в массиве для ключа tags (CodingKeys(stringValue: "tags", intValue: nil) в первом элементе root объекта (_JSONKey(stringValue: "Index 0", intValue: 0) - это не строка, а число (Expected to decode String but found a number instead).

То есть tags, вероятно, [Int]

...