gpt4 book ai didi

json - Codable 和 JSON 的问题

转载 作者:搜寻专家 更新时间:2023-11-01 06:53:00 24 4
gpt4 key购买 nike

我试图避免使用所有没有可编码的样板代码。

如果这是一个愚蠢的问题,我深表歉意,但为什么我在尝试使用 codable 解析 json 时会收到此错误?

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

json 端点的结构如下:

{
"businesses": [
{
"id": "FmGF1B-Rpsjq1f5b56qMwg",
"alias": "molinari-delicatessen-san-francisco",
"name": "Molinari Delicatessen",
"image_url": "https://s3-media3.fl.yelpcdn.com/bphoto/6He-NlZrAv2mDV-yg6jW3g/o.jpg",
"is_closed": false,
"url": "https://www.yelp.com/biz/molinari-delicatessen-san-francisco?adjust_creative=Js10QwuboHe9ZMZF31mwuw&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=Js10QwuboHe9ZMZF31mwuw",
"review_count": 1058,
"categories": [
{
"alias": "delis",
"title": "Delis"
}
],
"rating": 4.5,
"coordinates": {
"latitude": 37.79838,
"longitude": -122.40782
},
"transactions": [
"pickup",
"delivery"
],
"price": "$$",
"location": {
"address1": "373 Columbus Ave",
"address2": "",
"address3": "",
"city": "San Francisco",
"zip_code": "94133",
"country": "US",
"state": "CA",
"display_address": [
"373 Columbus Ave",
"San Francisco, CA 94133"
]
},
"phone": "+14154212337",
"display_phone": "(415) 421-2337",
"distance": 1453.998141679007
}

}

我有一个我创建的结构

struct Businesses: Codable {

var name:String
var image_url:String
var is_closed:Bool
var location:[String:String]
var display_phone:String
var url:String

}

这是我尝试使用 Codable 的方式:

do{
let jsonData = response.data

//created the json decoder
let decoder = JSONDecoder()

//using the array to put values
self.searchResults = [try decoder.decode(Businesses.self, from: jsonData!)]

最佳答案

这是一个非常常见的错误,您忽略了根对象,它当然没有键 name

你会得到另一个错误,location is not [String:String]

struct Root : Decodable {
let businesses : [Business]
}

// Name this kind of struct in singular form

struct Business : Decodable {
let name: String
let imageUrl: URL
let isClosed: Bool
let location: Location
let displayPhone: String
let url: URL
}

struct Location : Decodable {
let address1, address2, address3: String
let city, zipCode, country, state: String
let displayAddress: [String]
}

...

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
do {
let jsonData = response.data
let result = try decoder.decode(Root.self, from: jsonData!)
self.searchResults = result.businesses
} catch { print(error) }

关于json - Codable 和 JSON 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55873545/

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