简体   繁体   English

Swift:如何将带有Alamofilre或SwiftyJSON的JSON字符串转换为ObjectMapper?

[英]Swift: How to Convert JSON String with Alamofilre or SwiftyJSON to ObjectMapper?

I'm currently using ObjectMapper for Swift for mapping JSON Object from API to model Object 我目前正在使用ObjectMapper for Swift将JSON Object从API映射到模型Object

but my restful api return API look like this: 但我的restful api返回API看起来像这样:

{
       success: true,
       data: 
       [{  
          "stats":{  
             "numberOfYes":0,
             "numberOfNo":2,
             "progress":{  
                "done":false,
                "absolute":"2/100",
                "percent":2
             }
          },
          "quickStats":null,
          "uid":5,
          "name":"Flora",
          "imageArray":[  
             "http://s3.com/impr_5329beac79400000",
             "http://s3.com/impr_5329beac79400001"
          ],
          "metaData":{  
             "description":"Floral Midi Dress",
             "price":"40$"
          }
       }]

}

In data node is array i can't look up to mapping with this code 在数据节点是数组我无法查找与此代码的映射

let json = JSON(responseObject!)

for tests in json["impressions"][0] {
  let test = Mapper<myTests>().map(tests)
  println(test?.impressionID)
}

How should I fix? 我该怎么办? Thanks 谢谢

** Edited ** I found solution similar @tristan_him ** 编辑 ** 我找到类似@tristan_him的解决方案

ObjectModel mapping structure ObjectModel映射结构

class Response: Mappable {
    var success: Bool?
    var data: [Data]?

    required init?(_ map: Map) {
        mapping(map)
    }

    func mapping(map: Map) {
        success <- map["success"]
        data <- map["data"]
    }
}

class Data: Mappable {
    var uid: Int?
    var name: String?
    // add other field which you want to map        

    required init?(_ map: Map) {
        mapping(map)
    }

    func mapping(map: Map) {
        uid <- map["uid"]
        name <- map["name"]
    }
}

Mapping with Alamofire response 使用Alamofire响应进行映射

let response: Response = Mapper<Response>().map(responseObject)!

for item in response.data! {
    let dataModel: Data = item
    println(dataModel.name)
}

You can map the JSON above by using the following class structure: 您可以使用以下类结构映射上面的JSON:

class Response: Mappable {
    var success: Bool?
    var data: [Data]?

    required init?(_ map: Map) {
        mapping(map)
    }

    func mapping(map: Map) {
        success <- map["success"]
        data <- map["data"]
    }
}

class Data: Mappable {
    var uid: Int?
    var name: String?
    // add other field which you want to map        

    required init?(_ map: Map) {
        mapping(map)
    }

    func mapping(map: Map) {
        uid <- map["uid"]
        name <- map["name"]
    }
}

Then you can map it as follows: 然后你可以按如下方式映射它:

let response = Mapper<Response>().map(responseObject)
if let id = response?.data?[0].uid {
    println(id)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM