我有3个对象(国籍,服务和包),我从JSON响应得到它们作为这些对象的3个数组..我想从JSON响应中解析它们......
课程是:
struct Root2 : Decodable {
let nationalities : [Nationalities]
let services : [Services]
let packages : [Packages]
}
struct Packages : Decodable {
let id: Int
let name: String
let idService: Int
let nationality: String
let totalPrice: Int
let visitsPerWeek: Int
let excludedDays: String
let excludedShifts: String
let excludedDates: String
let extraVisits: Int
let dateEnabled: String
let dateDisabled: String
let allowedFrom: String
let allowedTo: String
let visitType: String
let createdAt: String?
let updatedAt: String?
}
struct Nationalities : Decodable{
let id: Int
let name: String
let createdAt: String?
let updatedAt: String?
}
struct Services : Decodable{
let id: Int
let name, description: String
let createdAt: String?
let updatedAt: String?
}
我和每个人都喜欢这样的课程:
class Service : NSObject, NSCoding {
var id: Int
var name, desc: String
var createdAt: String?
var updatedAt: String?
init(id: Int, name: String, desc: String) {
self.id = id
self.name = name
self.desc = desc
}
required convenience init(coder aDecoder: NSCoder) {
let id = aDecoder.decodeInteger(forKey: "id")
let name = aDecoder.decodeObject(forKey: "name") as! String
let desc = aDecoder.decodeObject(forKey: "desc") as! String
self.init(id: id, name: name, desc: desc)
}
func encode(with aCoder: NSCoder) {
aCoder.encode(id, forKey: "id")
aCoder.encode(name, forKey: "name")
aCoder.encode(desc, forKey: "desc")
}
}
我正在使用它:
func GetServicesPackagesNationalities(){
let link: String = "my link"
guard let url = URL(string: link) else {
print("Error: cannot create URL")
return
}
let urlRequest = URLRequest(url: url)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: urlRequest) {
(data, response, error) in
guard error == nil else {
print("error calling GET on /public/api/services")
print(error!)
return
}
guard let responseData = data else {
print("Error: did not receive data")
return
}
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let result = try decoder .decode(Root2.self, from: responseData)
var nationalities = [Nationality]()
for nationality in result.nationalities{
let newnationality = Nationality(id: nationality.id, name: nationality.name)
nationalities.append(newnationality)
print(newnationality.name)
}
var services = [Service]()
for service in result.services {
let newservice = Service(id: service.id, name: service.name, desc: service.description)
services.append(newservice)
print(newservice.name)
}
var packages = [Package]()
for package in result.packages{
let newpackage = Package(id: package.id, name: package.name, idService: package.idService, nationality: package.nationality, totalPrice: package.totalPrice, visitsPerWeek: package.visitsPerWeek, excludedDays: package.excludedDays, excludedShifts: package.excludedShifts, excludedDates: package.excludedDates, extraVisits: package.extraVisits ,dateEnabled: package.dateEnabled , dateDisabled: package.dateDisabled, allowedFrom: package.allowedFrom, allowedTo: package.allowedTo ,visitType: package.visitType)
packages.append(newpackage)
print(newpackage.name)
}
}catch {
print("error trying to convert data to JSON")
return
}
}
task.resume()
}
我将永远得到这个:
尝试将数据转换为JSON时出错
我的json是:
{
"nationalities": [
{
"id": 1,
"name": "Saudi Arabia",
"created_at": "2018-04-24 05:50:41",
"updated_at": "2018-04-24 06:35:29",
"deleted_at": null
},
{
"id": 2,
"name": "Bahrain",
"created_at": "2018-04-24 05:52:52",
"updated_at": "2018-04-24 05:52:52",
"deleted_at": null
},
],
"services": [
{
"id": 1,
"name": "Nad",
"description": "Nad ",
"created_at": null,
"updated_at": null,
"deleted_at": null
},
{
"id": 2,
"name": "Reay",
"description": "Re ",
"created_at": null,
"updated_at": null,
"deleted_at": null
},
],
"packages": [
{
"id": 1,
"name": "Gold Package",
"id_service": 1,
"nationality": "4",
"total_price": 1000,
"visits_per_week": 2,
"excluded_weekdays": "null",
"excluded_shifts": "null",
"excluded_dates": "1111-11-11",
"extra_visits": 1,
"date_enabled_from": "2018-04-01",
"date_enabled_to": "2018-04-30",
"date_allowed_from": "2018-04-05",
"date_allowed_to": "2018-04-30",
"visit_type": "Multi",
"created_at": "2018-04-26 11:18:45",
"updated_at": "2018-04-26 11:18:45",
"deleted_at": null
}
]
}
我不知道我做错了什么..因为我尝试了同样的两个对象并且工作得很好..
有人可以告诉我,我做错了吗?
在userdefaults中使用它们:
存储
let userDefaults = UserDefaults.standard
let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: services)
userDefaults.set(encodedData, forKey: "services")
userDefaults.synchronize()
检索:
let decoded = userDefaults.object(forKey: "services") as! Data
let decodedService = NSKeyedUnarchiver.unarchiveObject(with: decoded) as! [Service]
for service in decodedService {
print(service.name)
}
答案 0 :(得分:0)
查看Nationality
和Nationalities
您应该使用Nationalities
来解析您的JSON响应。
您应该这样做,因为您在Nationalities
Root2
个对象
var nationalities = [Nationalities]()
for nationality in result.nationalities{
let newnationality = Nationalities(id: nationality.id, name: nationality.name)
nationalities.append(newnationality)
print(newnationality.name)
}
Services
和Packages
相同,请找到它。
答案 1 :(得分:0)
请从不在catch
子句中打印无意义的文字字符串,始终打印实际错误,它会告诉您确切的错误
} catch {
print(error)
}
在Package
中存在很多问题,以下是错误消息(以及修复它们的建议):
"没有与密钥CodingKeys相关联的值(stringValue:\" excludedDays \",转换为excluded_days。"
excluded_days
。 删除该属性或将其声明为可选(String?
) "没有与密钥CodingKeys相关联的值(stringValue:\" dateEnabled \"转换为date_enabled。"
dateEnabledFrom
"没有与密钥CodingKeys相关联的值(stringValue:\" dateDisabled \"转换为date_disabled。"
date_disabled
。 删除该属性或将其声明为可选(String?
) "没有与密钥CodingKeys相关联的值(stringValue:\" allowedFrom \",intValue:nil)(\" allowedFrom \"),转换为allowed_from。 "
dateAllowedFrom
"没有与密钥CodingKeys相关的值(stringValue:\" allowedTo \",intValue:nil)(\" allowedTo \"),转换为allowed_to。 "
dateAllowedTo
注意:
为什么要为Nationality, Service, Package
使用另一个额外的课程?它们似乎是多余的。如果你真的需要引用语义将JSON解码成类。