Codable和JSON的问题
我试图避免使用所有没有编码的样板代码 如果这是一个愚蠢的问题,我很抱歉,但为什么我在尝试用codable解析json时会出现这个错误呢Codable和JSON的问题,json,swift,codable,jsonparser,Json,Swift,Codable,Jsonparser,我试图避免使用所有没有编码的样板代码 如果这是一个愚蠢的问题,我很抱歉,但为什么我在尝试用codable解析json时会出现这个错误呢 keyNotFound(CodingKeys(stringValue: "name", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"name
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!)]
这是一个非常常见的错误,您忽略了根对象,当然,它没有键
名称
您将得到另一个错误,位置
为非[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) }
是的,我确实犯了那个错误。我是来告诉你,一旦我得到了你最初的答案。我刚把它删掉了。非常感谢。