gpt4 book ai didi

json - 解码 Json 不工作,也不报错

转载 作者:行者123 更新时间:2023-11-28 11:35:38 26 4
gpt4 key购买 nike

我正在尝试解码以下 json:

    [
{
"breeds":[
{
"weight":{
"imperial":"65 - 75",
"metric":"29 - 34"
},
"height":{
"imperial":"21 - 28",
"metric":"53 - 71"
},
"id":14,
"name":"American Foxhound",
"country_code":"US",
"bred_for":"Fox hunting, scent hound",
"breed_group":"Hound",
"life_span":"8 - 15 years",
"temperament":"Kind, Sweet-Tempered, Loyal, Independent, Intelligent, Loving"
}
],
"id":"p4xvDeEpW",
"url":"https://cdn2.thedogapi.com/images/p4xvDeEpW.jpg",
"width":680,
"height":453
}
]

我将我的模型设置为:

struct Request: Decodable {
let response: [Response]
}

struct Response: Decodable {
let breeds: [Dog]
let url: String
}

struct Dog: Decodable {
let weight: Measurement
let height: Measurement
let name: String
let countryCode: String?
let breedGroup: String
let lifeSpan: String
let temperament: String
let origin: String?
}

struct Measurement: Decodable {
let imperial: String
let metric: String
}

我调用 API 如下:

func fetchDogs(with request: URLRequest, completion: @escaping (([Dog]?, String?, Error?) -> ())) {
URLSession.shared.dataTask(with: request) { (data, response, error) in
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase

guard let data = data,
let request = try? decoder.decode(Request.self, from: data) else {
completion(nil, nil, error)
return
}

completion(request.response[0].breeds, request.response[0].url, nil)
}.resume()
}

但它总是命中守卫 completion(nil, nil, error) 行,我不确定为什么我不确定如何将 JSON 的前几行分开以开始关闭。使用:

struct Request: Decodable {
let response: [Response]
}

好像不太对。如果我更新请求以解码 Response 结构,它仍然会触发 guard 。

我的请求生成器如下所示:

struct RequestBuilder {
private let baseURLString: String

static var defaultBuilder: RequestBuilder {
return RequestBuilder(
baseURLString: Constant.URL.dogsBase
)
}

func dogsRequest() -> URLRequest {
return dogRequest(path: Constant.Path.search)
}

private func dogRequest(path: String) -> URLRequest {
guard var components = URLComponents(string: baseURLString) else {
preconditionFailure(Constant.PreconditionFailure.baseURL)
}

components.path = path

guard let url = components.url else {
preconditionFailure(Constant.PreconditionFailure.baseURL)
}
var request = URLRequest(url: url)
request.setValue(Constant.Key.dogs, forHTTPHeaderField: "x-api-key")

return request
}
}

可以找到api here

最佳答案

问题是,当您将 Request.self 传递给 decode.decode 时,JSONDecoder 期望找到一个 Dictionary 的键是 response 因为你声明了 Request

您只需将[Response].self 传递给decode 方法即可。

guard let data = data,
let request = try? decoder.decode([Response].self, from: data) else {
completion(nil, nil, error)
return
}

如果您没有使用 try? 屏蔽解码错误,您会立即从错误消息中看到问题:

typeMismatch(Swift.Dictionary, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary but found an array instead.", underlyingError: nil))

当您不确定您的代码是否有效时,您应该始终在 do-catch block 中使用普通的 try 语句,因为这样您实际上可以查看错误消息。 JSONDecoder 抛出非常有用的错误,所以我建议您永远不要使用 try? 将它们屏蔽为 nil

关于json - 解码 Json 不工作,也不报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55519838/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com