查看收到 json 以调试 JSONDecoder 错误

View received json to debug JSONDecoder error

我目前正在使用以下流程调用 api 并解码响应:

            .dataTaskPublisher(for: urlRequest)
            .mapError { error -> NetworkClientError in
                print(error)
                return NetworkClientError.network(description: error.localizedDescription)
            }
            .tryMap { element -> Data in
                guard let httpResponse = element.response as? HTTPURLResponse,
                      httpResponse.statusCode == 200 else {
                    throw NetworkClientError.network(description: URLError(.badServerResponse).localizedDescription)
                }
                return element.data
            }
            .decode(type: T.self, decoder: decoder)
            .mapError { error in
                print(error)
                return NetworkClientError.parsing(description: error.localizedDescription)
            }
            .receive(on: queue)
            .retry(retries)
            .eraseToAnyPublisher()

当我调用它时,我得到一个 200 响应,但还有一个解码错误:

keyNotFound(CodingKeys(stringValue: "leagues", intValue: nil), Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "data", intValue: nil), CodingKeys(stringValue: "leagues", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: \"leagues\", intValue: nil) (\"leagues\").", underlyingError: nil))
parsing(description: "The data couldn’t be read because it is missing.")

我想做的就是查看已收到的 json,以便我可以了解它的预期内容。我可以看到我给它的模型说期望值 leagues 但这不是它能找到的。我怎样才能看到它找到了什么?

好的,我通过在守卫后面添加以下内容解决了这个问题。

                do {
                    if let json = try JSONSerialization.jsonObject(with: element.data, options: []) as? [String: Any] {

                        print(json)
                    }
                } catch let error as NSError {
                    print("Failed to load: \(error.localizedDescription)")
                }