首页 > 解决方案 > 如何使用对象映射器 Swift 映射字典数组

问题描述

嗨,我像这样使用对象映射器编写模型类。

在这里,我得到了 Array of Dictionary 格式的响应。

在这种情况下我们如何映射响应请在下面找到我的代码。

class Modelclass : Mappable{

    var mainsite : [Mainsite]!

    required init?(map: Map) { }

    func mapping(map: Map) {
        mainsite    <- map["Mainsite"]
    }
}


class Mainsite : Mappable{

    var categoryId : String!
    var cPath : String!
    var level : Int!
    var name : String!
    var parentID : String!
    var subItems : [SubItem]!

    required init?(map: Map) { }

    func mapping(map: Map) {
        categoryId    <- map["CategoryId"]
        cPath    <- map["cPath"]
        level    <- map["level"]
        name    <- map["Name"]
        parentID    <- map["ParentID"]
        subItems    <- map["SubItems"]
    }
}

在这里,我尝试使用以下代码映射响应。

    func ApiResponse(){
    Alamofire.request("https://www.furnitureinfashion.net/menu_category.php", method: .get, parameters: nil, headers: nil).responseJSON { (response) in

        if response.data != nil
        {
            let data = Mapper<Modelclass>().map(JSON: response)

        }else{
            print(response.error?.localizedDescription ?? "")
        }
    }
}

标签: iosarraysswiftapidictionary

解决方案


如果你在这里分享你的回应会容易得多。我假设您正在获取 Mainsite 对象的数组

 if response.data != nil
    {
        let data = Mapper<Mainsite>().map(JSONArray: response)

    }

如果你得到的对象是 Mainsite Model 的数组,那么你可以使用 ObjectMapper 的 map JSON Array 方法。它接受两种形式的输入,一种是 AnyObject,另一种是 [[String : Any]],它将返回 Mainsite 模型的数组


推荐阅读