如何使用 Alamofire 使用 JSON 数据填充我的对象数组
How to populate my object Array with JSON data using Alamofire
我是 Swift 的新手,我正在尝试为我的 woocommerce 商店创建一个移动应用程序。我用名称、价格和图像源创建了一个产品 class。我还创建了另一个 productBank 来存储我的产品对象,但我不知道如何使用 Alamofire 用 JSON 填充它。
class Simpleproduct {
var productName: String
var productPrice: Int
var ProductImage: String
init(price: Int, name: String, image: String) {
productName = name
productPrice = price
ProductImage = image
}
}
class Productbank {
var productlist = [Simpleproduct]()
init() {
productlist.append(Simpleproduct(price: 5, name: "productname", image: "imagesrc"))
productlist.append(Simpleproduct(price: 5, name: "productname", image: "imagesrc"))
productlist.append(Simpleproduct(price: 5, name: "productname", image: "imagesrc"))
productlist.append(Simpleproduct(price: 5, name: "productname", image: "imagesrc"))
// [...]
再次发布我的答案,因为它已被删除...
我推荐使用 AlamoFireObjectMapper,它是一个很酷且易于使用的库:
https://github.com/tristanhimmelman/AlamofireObjectMapper
您的代码将是这样的(您将收到 json 自动映射到您的对象模型):
对象模型
class EncuestaModel:Object, Mappable{
@objc dynamic var Id = 0
@objc dynamic var Name:String?
@objc dynamic var CreationDate:Date?
@objc dynamic var Status = 0
@objc dynamic var Default = false
required convenience init?(map: Map) {
self.init()
}
}
对于 Alamofire 请求:
func getEncuestas(){
let url = "yourApiUrl"
Alamofire.request(url).responseObject {(response:DataResponse<LoginResultModel>) in
if let result = response.result.value {
//do your code here
}
}
}
我是 Swift 的新手,我正在尝试为我的 woocommerce 商店创建一个移动应用程序。我用名称、价格和图像源创建了一个产品 class。我还创建了另一个 productBank 来存储我的产品对象,但我不知道如何使用 Alamofire 用 JSON 填充它。
class Simpleproduct {
var productName: String
var productPrice: Int
var ProductImage: String
init(price: Int, name: String, image: String) {
productName = name
productPrice = price
ProductImage = image
}
}
class Productbank {
var productlist = [Simpleproduct]()
init() {
productlist.append(Simpleproduct(price: 5, name: "productname", image: "imagesrc"))
productlist.append(Simpleproduct(price: 5, name: "productname", image: "imagesrc"))
productlist.append(Simpleproduct(price: 5, name: "productname", image: "imagesrc"))
productlist.append(Simpleproduct(price: 5, name: "productname", image: "imagesrc"))
// [...]
再次发布我的答案,因为它已被删除...
我推荐使用 AlamoFireObjectMapper,它是一个很酷且易于使用的库:
https://github.com/tristanhimmelman/AlamofireObjectMapper
您的代码将是这样的(您将收到 json 自动映射到您的对象模型):
对象模型
class EncuestaModel:Object, Mappable{
@objc dynamic var Id = 0
@objc dynamic var Name:String?
@objc dynamic var CreationDate:Date?
@objc dynamic var Status = 0
@objc dynamic var Default = false
required convenience init?(map: Map) {
self.init()
}
}
对于 Alamofire 请求:
func getEncuestas(){
let url = "yourApiUrl"
Alamofire.request(url).responseObject {(response:DataResponse<LoginResultModel>) in
if let result = response.result.value {
//do your code here
}
}
}