如何映射具有数据数组的数据

时间:2019-01-10 10:16:22

标签: ios iphone swift alamofire xcode10.1

我的答复是:

  [
  {
    "menu_code" : "NDS",
    "items" : [
      {
        "unit" : "Nos",
        "name" : "Chapathi\/Pulkas",
        "quantity" : 2
      },
      {
        "unit" : "Cup",
        "name" : "Palya\/Curry",
        "quantity" : 1
      }
    ],
    "is_active" : 1,
    "image" : "nds.jpg",
    "menu_name" : "Normal Diet South"
  },
  {
    "menu_code" : "NCCD",
    "items" : [
      {
        "menu_code" : "NDS",
        "name" : "Monday"
      },
      {
        "menu_code" : "NDN",
        "name" : "Tuesday"
      }
    ],
    "is_active" : 1,
    "image" : "NCCD.jpg",
    "menu_name" : "Normal Combo Corporate Diet"
  }
]

我今天有2种格式。在这两种格式中,只有我的数据会来自响应。我需要在集合视图中显示它们。

我的api调用:

func getAllCatogory(){

        TransportManager.sharedInstance.AllCatogory { (dt, err) in

            if let _ = err{

            }else{
                if let data = dt as? String {
                   let pro = Mapper<AllCatagories>().map(JSONString: data)
                print(data) // getting data
                print(pro as Any) // getting nil

                }

            }
        }
    }

我的模特:

class AllCatagories: Mappable{

    var menu_code = ""
    var items: Array<AllCatProducts> = []
    var is_active = 0
    var image = ""
    var menu_name = ""

    required init?(map: Map) {

    }

    init() {

    }

    func mapping(map: Map) {

        menu_name <- map["menu_name"]
        is_active <- map["is_active"]
        menu_code <- map["menu_code"]
        image <- map["image"]
       items <- map["items"]
    }
}

下面,我为json中的项目创建了另一个模型类。

class AllCatProducts: Mappable{

    var name = ""
    var quantity = 0
    var unit = ""
    var menu_code = ""



    required init?(map: Map) {

    }

    init() {

    }

    func mapping(map: Map) {
        name <- map["name"]
        quantity <- map["quantity"]
        unit <- map["unit"]
        menu_code <- map["menu_code"]
    }
}

问题是我的pro没什么了。不确定我什么时候做错了。

谢谢

1 个答案:

答案 0 :(得分:-1)

您可以尝试

struct AllCatagories: Codable {
    let menuCode: String
    let items: [AllCatProducts]
    let isActive: Int
    let image, menuName: String
}

struct AllCatProducts: Codable {
    let unit: String?
    let name: String
    let quantity: Int?
    let menuCode: String? 
}

do {
   let decoder = JSONDecoder()
   decoder.keyDecodingStrategy = .convertFromSnakeCase
   guard let str = dt as? String else { return }
   let res  = try decoder.decode([AllCatagories].self, from:str.data(using: .utf8)!)
   print(res)
 }
 catch {
  print(error)
 }