无法解析 codable 中的数据。我能够获取数据,但是一旦我使用解码功能,我就会出错
Not able to parse data in codable. I am able to fetch data but some how once I use decode function I get error
我无法使用 decodable 解析数据。我能够获取数据但无法使用可解码函数对其进行解析。它说
unresolved identifier 'data' in that function.
试了各种方法还是不行
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
var str = "Hello, playground"
struct category : Codable {
let success: Bool
let list: [List]
let slide: [String]
}
// MARK: - List
struct List: Codable {
let id, categoryName: String
let subcategory: [Subcategory]
}
// MARK: - Subcategory
struct Subcategory: Codable {
let subCategoryID: SubCategoryID
let subCategoryName, categoryID: String
let banner: String
enum CodingKeys: String, CodingKey {
case subCategoryID = "sub_category_id"
case subCategoryName = "sub_category_name"
case categoryID = "category_id"
case banner
}
}
enum SubCategoryID: Codable {
case integer(Int)
case string(String)
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let x = try? container.decode(Int.self) {
self = .integer(x)
return
}
if let x = try? container.decode(String.self) {
self = .string(x)
return
}
throw DecodingError.typeMismatch(SubCategoryID.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for SubCategoryID"))
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .integer(let x):
try container.encode(x)
case .string(let x):
try container.encode(x)
}
let session = URLSession(configuration: .default)
var datatask : URLSessionDataTask?
let url = "http://comus.in/co/webservice/getCategoryList.php"
var items = [URLQueryItem]()
var myURL = URLComponents(string: url)
let param = ["vendorId":"32"]
for (key,value) in param {
items.append(URLQueryItem(name: key, value: value))
}
myURL?.queryItems = items
let request = URLRequest(url: (myURL?.url)!)
datatask = session.dataTask(with: request, completionHandler: {data, response, error in
if error == nil {
let receivedData = try? JSONSerialization.jsonObject(with: data!, options: []) as! [String: Any]
print(receivedData!)
let listings = try? JSONDecoder().decode(List.self , from: data)
if let listings = listings{
}
}
})
datatask?.resume()
}
}
这是一个简单的语法错误。因为您在 decode
函数中的 data
之后错过了 !
。另外正如@Joakim Danielson 在评论中建议的那样,当您不知道发生了什么时,不要 try?
。所以改变这个:
let listings = try? JSONDecoder().decode(List.self , from: data)
if let listings = listings{
}
对此:
do {
let listings = try JSONDecoder().decode(List.self , from: data!)
print(listings)
} catch {
print(error)
}
我无法使用 decodable 解析数据。我能够获取数据但无法使用可解码函数对其进行解析。它说
unresolved identifier 'data' in that function.
试了各种方法还是不行
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
var str = "Hello, playground"
struct category : Codable {
let success: Bool
let list: [List]
let slide: [String]
}
// MARK: - List
struct List: Codable {
let id, categoryName: String
let subcategory: [Subcategory]
}
// MARK: - Subcategory
struct Subcategory: Codable {
let subCategoryID: SubCategoryID
let subCategoryName, categoryID: String
let banner: String
enum CodingKeys: String, CodingKey {
case subCategoryID = "sub_category_id"
case subCategoryName = "sub_category_name"
case categoryID = "category_id"
case banner
}
}
enum SubCategoryID: Codable {
case integer(Int)
case string(String)
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let x = try? container.decode(Int.self) {
self = .integer(x)
return
}
if let x = try? container.decode(String.self) {
self = .string(x)
return
}
throw DecodingError.typeMismatch(SubCategoryID.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for SubCategoryID"))
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .integer(let x):
try container.encode(x)
case .string(let x):
try container.encode(x)
}
let session = URLSession(configuration: .default)
var datatask : URLSessionDataTask?
let url = "http://comus.in/co/webservice/getCategoryList.php"
var items = [URLQueryItem]()
var myURL = URLComponents(string: url)
let param = ["vendorId":"32"]
for (key,value) in param {
items.append(URLQueryItem(name: key, value: value))
}
myURL?.queryItems = items
let request = URLRequest(url: (myURL?.url)!)
datatask = session.dataTask(with: request, completionHandler: {data, response, error in
if error == nil {
let receivedData = try? JSONSerialization.jsonObject(with: data!, options: []) as! [String: Any]
print(receivedData!)
let listings = try? JSONDecoder().decode(List.self , from: data)
if let listings = listings{
}
}
})
datatask?.resume()
}
}
这是一个简单的语法错误。因为您在 decode
函数中的 data
之后错过了 !
。另外正如@Joakim Danielson 在评论中建议的那样,当您不知道发生了什么时,不要 try?
。所以改变这个:
let listings = try? JSONDecoder().decode(List.self , from: data)
if let listings = listings{
}
对此:
do {
let listings = try JSONDecoder().decode(List.self , from: data!)
print(listings)
} catch {
print(error)
}