【问题标题】:How to populate my object Array with JSON data using Alamofire如何使用 Alamofire 用 JSON 数据填充我的对象数组
【发布时间】:2019-09-11 22:21:03
【问题描述】:

我是 Swift 新手,我正在尝试为我的 woocommerce 商店创建一个移动应用程序。我创建了一个带有名称、价格和图像 src 的产品类。我还创建了另一个 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"))
        // [...]

【问题讨论】:

  • 您是否正在检索产品以通过需要使用 Alamofire 的端点显示,因为我在您发布的代码中没有看到它?您需要阅读Codable 协议。如果您从端点获取数据,我建议将您的类转换为符合Codable 协议的struct。这将使您能够放弃初始化程序(假设您得到一个干净的 JSON,其中 Ints 不像字符串等愚蠢的东西)

标签: json swift alamofire


【解决方案1】:

再次发布我的答案,因为它已被删除...

我推荐使用 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
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 2018-07-07
    • 2017-02-10
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    相关资源
    最近更新 更多