Swift 5无法从API调用映射JSON对象



我有一个API调用,它返回一个JSON对象,如下所示:

{"took":19,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{"value":1,"relation":"eq"},"max_score":11.1074705,"hits":[{"_index":"test_data","_type":"test_type","_id":"dAT6YHoB2mxCCW1k6TLU","_score":11.1074705,"_source":{"name": "mz1v60MiJ", "age": 41706, "last_updated": 1625601405000}}]}}

当我试图将它映射到一个对象时,我会得到以下错误:

Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "name", intValue: nil),
Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "hits", intValue: nil),
CodingKeys(stringValue: "hits", intValue: nil),
_JSONKey(stringValue: "Index 0", intValue: 0)],
debugDescription: "No value associated with key CodingKeys(stringValue: "name", intValue: nil) ("name").",
underlyingError: nil))

这是userViewModel.swift的代码,我在这里调用API:

class apiCall {
func getUsers(completion:@escaping ([User]) -> ()) {
guard let url = URL(string: "http://192.168.1.5:9200/_search?q=mz1v60MiJ") else { return }
URLSession.shared.dataTask(with: url) { (data, _, _) in
let users = try! JSONDecoder().decode(UserResponse.self, from: data!)
print(users)

DispatchQueue.main.async {
completion(users.hits.hits)
}
}
.resume()
}
}

这是对象的UserModel文件:

struct User: Codable, Identifiable {
let id = UUID()
let name: String
let age: Int
let last_updated: Date
}
struct UserHits: Codable {
let hits: [User]
}
struct UserResponse: Codable {
let hits: UserHits
}

我需要的数据在第二个";点击";JSON,但它似乎找不到数据。

您需要在UserHits和User之间使用一个新类型

struct HitData: Codable {
let source: User
enum CodingKeys: String, CodingKey {
case source = "_source"
}
}
struct UserHits: Codable {
let hits: [HitData]
}

如果您想通过给属性一个正确的类型来添加id属性,您还需要修复User结构

struct User: Codable, Identifiable {
let id: UUID = UUID()
let name: String
let age: Int
let lastUpdated: Date
}

最后,在解码时,您应该设置一个日期解码策略,以便正确解析日期值(并使用convertFromSnakeCase,这样当json键有一个属性名称时,您就不需要在属性名称中输入_(

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .millisecondsSince1970
decoder.keyDecodingStrategy = .convertFromSnakeCase

您需要为&quot_源";密钥

相关内容

  • 没有找到相关文章

最新更新