我正在尝试从JSON响应中获取一些价格数据并将其保存在用户默认值中...
价格等级是:
import Foundation
struct Prices : Decodable{
let id, id_service: Int
let nationality: String
let price: Int
let createdAt: String?
let updatedAt: String?
}
class Price : NSObject, NSCoding {
var id, id_service: Int
var nationality: String
var price: Int
var createdAt: String?
var updatedAt: String?
init(id: Int, id_service: Int, nationality: String, price: Int) {
self.id = id
self.id_service = id_service
self.nationality = nationality
self.price = price
}
required convenience init(coder aDecoder: NSCoder) {
let id = aDecoder.decodeInteger(forKey: "id")
let id_service = aDecoder.decodeInteger(forKey: "id_service")
let nationality = aDecoder.decodeObject(forKey: "nationality") as! String
let price = aDecoder.decodeInteger(forKey: "price")
self.init(id: id, id_service: id_service, nationality: nationality, price: price)
}
func encode(with aCoder: NSCoder) {
aCoder.encode(id, forKey: "id")
aCoder.encode(id_service, forKey: "id_service")
aCoder.encode(nationality, forKey: "nationality")
aCoder.encode(price, forKey: "price")
}
}
我要求这样做的方法是:
func GetPrices() {
let todoEndpoint: String = "my link"
guard let url = URL(string: todoEndpoint) 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 prices1 = try decoder.decode([Prices].self, from: responseData)
print("1")
var prices = [Price]()
for price in prices1{
let newprice = Price(id: price.id, id_service: price.id_service,nationality: price.nationality, price: price.price)
print("2")
prices.append(newprice)
print(newprice.nationality)
}
var userDefaults = UserDefaults.standard
let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: prices)
userDefaults.set(encodedData, forKey: "prices")
userDefaults.synchronize()
let decoded = userDefaults.object(forKey: "prices") as! Data
let decodedPrice = NSKeyedUnarchiver.unarchiveObject(with: decoded) as! [Price]
for price in decodedPrice {
print(price.nationality)
}
} catch {
print("error trying to convert data to JSON")
return
}
}
task.resume()
}
我拥有的JSON就像这样(它现在只有一个......但是它的数组):
[
{
"id": 1,
"id_service": 2,
"nationality": "Phili",
"price": 150,
"created_at": "2018-04-23 11:43:40",
"updated_at": "2018-04-23 11:43:40",
"deleted_at": null
}
]
问题是我总是收到此消息:尝试将数据转换为JSON时出错
为什么呢?我做错了什么?怎么解决这个?
答案 0 :(得分:1)
您正在使用.convertFromSnakeCase进行解码,因此您的属性应该是骆驼套管。
decoder.keyDecodingStrategy = .convertFromSnakeCase
所以要修复,请将您的属性名称id_service更改为idService,就像这样。
struct Prices : Decodable{
let id, idService: Int
let nationality: String
let price: Int
let createdAt: String?
let updatedAt: String?
}
为了更好地理解,您也可以查看.useDefaultKeys https://developer.apple.com/documentation/foundation/jsondecoder.keydecodingstrategy/2949131-usedefaultkeys