JSON 解码正在打印错误,而不是打印解码后的数据

JSON Decoding is printing an error, instead of printing decoded data

我正在尝试从 JSON 数组中获取 authordownload_url 下面。

[
{
"id": "0",
"author": "Alejandro Escamilla",
"width": 5616,
"height": 3744,
"url": "https://unsplash.com/photos/yC-Yzbqy7PY",
"download_url": "https://picsum.photos/id/0/5616/3744"
},
{
"id": "1",
"author": "Alejandro Escamilla",
"width": 5616,
"height": 3744,
"url": "https://unsplash.com/photos/LNRyGwIJr5c",
"download_url": "https://picsum.photos/id/1/5616/3744"
} ]

创建了一个 ImageStruct 以将 JSON 的数据转换为 ImageStruct 对象。

struct ImageData: Codable {
var author: String
var dataURL : String
}

我的 JSON 解码处理是在名为 JSONDecodeHandler 的结构函数中完成的。处理解码的函数称为 jsonDecode,输入参数为“data

struct JSONDecodeHandler {

static let shared = JSONDecodeHandler()
let decoder = JSONDecoder()

func jsonDecode(data: Data) {
    do {
        let decodedData = try decoder.decode([ImageData].self, from: data)
        print("decodedData is \(decodedData)")
    }
    catch {
        print("error on decoding JSON")
    }
}
}

此函数的输入是在名为 APIHandler

的结构中给出的
struct APIHandler {

static let shared = APIHandler()

private let jsonUrl = "https://picsum.photos/v2/list"

public func getDataFromURL() {
    
    guard let stringToURL = URL(string: jsonUrl) else { return } // Creating URL FRom string.
    let urlSession = URLSession(configuration: .default) // Creating URLSession
    let urlSessionDataTask = urlSession.dataTask(with: stringToURL) { data, URLResponse, error in
        
        if error == nil {
            guard let unwrappedData = data else { return }
            JSONDecodeHandler.shared.jsonDecode(data: unwrappedData)
        }
        else {
            print("Error in getting data from URL")
        }
        
    }
    urlSessionDataTask.resume() // Resuming the DataTask
}

}

的completionBlock让urlSessionDataTask = urlSession.dataTaskreturns一个数据类型 调用了 数据 。此 data 是 JSONDecodeHandler 结构的函数 jsonDecode(data: ) 的输入参数。

最后,结构 APIHAndler 的函数 getDataFromURL() 在我的 viewController 的 viewDidLoad 中被调用,如下所示.

override func viewDidLoad() {
    APIHandler.shared.getDataFromURL()
}

通过执行这些步骤,我在终端上看到的是 “解码错误 JSON”,我在 JSONDecodeHandler 结构中写了为了捕捉错误。所以基本上我无法解码 JSON 数据。我在这里错过了什么? 谢谢

您的 struct ImageData 中的名称是 dataURL,但在 json 中您有 download_urlurl。这些名称必须与 Swift 匹配才能解码 json。您的 dataURL 字段可能是空的。