Json 没有与具有Unsplash API的密钥编码密钥关联的值

Json 没有与具有Unsplash API的密钥编码密钥关联的值,json,swift,codable,Json,Swift,Codable,我试图从Unsplash API解码这个json,但是ContentView显示为空白,如果我打印结果,那么我将得到“No value associated with key CodingKeys”错误。这很奇怪,因为我正在学习这个非常新的教程。我很困惑,因为这应该很简单,但我对斯威夫特还不熟悉 下面是全部错误 "No value associated with key CodingKeys(stringValue: \"total\", intValue: nil

我试图从Unsplash API解码这个json,但是ContentView显示为空白,如果我打印结果,那么我将得到“No value associated with key CodingKeys”错误。这很奇怪,因为我正在学习这个非常新的教程。我很困惑,因为这应该很简单,但我对斯威夫特还不熟悉

下面是全部错误

"No value associated with key CodingKeys(stringValue: \"total\", intValue: nil) (\"total\").", underlyingError: nil))
这是解码请求

class SearchObjectController : ObservableObject {
    static let shared = SearchObjectController()
    private init() {}
    
    var token = "my client id"
    @Published var results = [Result]()
    @Published var searchText : String = "Forest"
    
    func search () {
        let url = URL(string: "https://api.unsplash.com/search/photos?query=\(searchText)")
        var request = URLRequest(url: url!)
        request.httpMethod = "GET"
        request.setValue("Client-ID\(token)", forHTTPHeaderField: "Authorization")
        
        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            guard let data = data else {return}
            
            do {
                let res = try JSONDecoder().decode(Results.self, from: data)
                self.results.append(contentsOf: res.results)
                print(self.results)
            } catch {
                print(error)
            }
        }
        task.resume()
    }
}
这些是我为这个请求创建的结构

struct Results : Codable {
    var total : Int
    var results : [Result]
}

struct Result : Codable {
    var id : String
    var description : String?
    var urls : URLs
}

struct URLs : Codable {
    var small : String
}
unsphapi请求的json格式如下所示

{
  "total": 133,
  "total_pages": 7,
  "results": [
    {
      "id": "eOLpJytrbsQ",
      "created_at": "2014-11-18T14:35:36-05:00",
      "width": 4000,
      "height": 3000,
      "color": "#A7A2A1",
      "blur_hash": "LaLXMa9Fx[D%~q%MtQM|kDRjtRIU",
      "likes": 286,
      "liked_by_user": false,
      "description": "A man drinking a coffee.",
      "user": {
        "id": "Ul0QVz12Goo",
        "username": "ugmonk",
        "name": "Jeff Sheldon",
        "first_name": "Jeff",
        "last_name": "Sheldon",
        "instagram_username": "instantgrammer",
        "twitter_username": "ugmonk",
        "portfolio_url": "http://ugmonk.com/",
        "profile_image": {
          "small": "https://images.unsplash.com/profile-1441298803695-accd94000cac?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=32&w=32&s=7cfe3b93750cb0c93e2f7caec08b5a41",
          "medium": "https://images.unsplash.com/profile-1441298803695-accd94000cac?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=64&w=64&s=5a9dc749c43ce5bd60870b129a40902f",
          "large": "https://images.unsplash.com/profile-1441298803695-accd94000cac?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=128&w=128&s=32085a077889586df88bfbe406692202"
        },
        "links": {
          "self": "https://api.unsplash.com/users/ugmonk",
          "html": "http://unsplash.com/@ugmonk",
          "photos": "https://api.unsplash.com/users/ugmonk/photos",
          "likes": "https://api.unsplash.com/users/ugmonk/likes"
        }
      },
      "current_user_collections": [],
      "urls": {
        "raw": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f",
        "full": "https://hd.unsplash.com/photo-1416339306562-f3d12fefd36f",
        "regular": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&s=92f3e02f63678acc8416d044e189f515",
        "small": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&s=263af33585f9d32af39d165b000845eb",
        "thumb": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=200&fit=max&s=8aae34cf35df31a592f0bef16e6342ef"
      },
      "links": {
        "self": "https://api.unsplash.com/photos/eOLpJytrbsQ",
        "html": "http://unsplash.com/photos/eOLpJytrbsQ",
        "download": "http://unsplash.com/photos/eOLpJytrbsQ/download"
      }
    },
    // more photos ...
  ]
}

当请求无法处理时,许多API通常会在响应正文中返回错误的详细描述以及错误代码。这似乎是您的情况,因为JSON解析在结构的第一个字段上失败。首先检查dataTask的
completion
块中的
错误和
响应。statusCode
以确保API已成功处理您的请求并返回有效数据。

导致错误的原因是客户端ID和(令牌)之间缺少空格。

首先检查是否有错误,然后检查响应:
如果让httpResponse=response as?HTTPURLResponse{…}
,然后检查状态代码我更新了我的问题以显示完整错误。它表明缺少total,但如果我删除total,错误将变为“没有与键编码键关联的值(stringValue:\“results\”,intValue:nil)(“results\”,UnderlineError:nil))“您可能遇到了错误,而不是预期的响应。因此,请在
guard let data
行之后立即检查服务器错误打印收到的字符串:
print(字符串(数据:数据,编码:.utf8)!)
。我确信它揭示了一个JSON格式的错误。@SpikeThea,那将是一个不同的问题-所以,应该是一个不同的问题。但正如我所说——可能不是很清楚——您收到了一个服务器错误,JSON不是您期望解码的响应,因此您看到的解码错误
DecodingError
清楚地表明收到了有效的JSON,但显然不是预期的JSON。如果在完成块中发生错误,则
数据
nil
,且未到达解码行。如果发生服务器错误,服务器将发送HTML,您将在索引0处获得一个
意外字符。