简体   繁体   English

通过ObjectMapper映射Alamofire responseJSON

[英]Mappting Alamofire responseJSON via ObjectMapper

Note: I need to use ObjectMapper, and not AlamoFireObjectMapper. 注意:我需要使用ObjectMapper,而不是AlamoFireObjectMapper。

How do you map without going to JSON but from responseJSON data to map to User? 你如何映射而不是去JSON但是从responseJSON数据映射到用户? The following is trying to go from responseJSON to jsonn and then back again to data(being User). 以下是尝试从responseJSON转到jsonn然后再返回到数据(是User)。 I guess there must be a way? 我想一定有办法吗?

Or should I use responseData from AlamoFire? 或者我应该使用AlamoFire的responseData吗?

public class User: Mappable {
    var username: String?

    required public init?(map: Map) {

    }

    // Mappable
    public func mapping(map: Map) {
        username    <- map["username"]
    }
}


    Alamofire.request(
        url,
        method: .get,
        headers: headers_employees).responseJSON {
            response in
        // Map via ObjectMapper
        let [User] = Mapper<User>().map(JSONString: JSONString)

   }

The map function also accepts a JSONObject (Any) or a JSON dictionary ([String: Any]) . map函数还接受JSONObject (Any)JSON dictionary ([String: Any]) Depending on the type of the response object, you should use the appropriate method. 根据响应对象的类型,您应该使用适当的方法。

In your case use below code to map JSONResponse 在您的情况下使用下面的代码来映​​射JSONResponse

Alamofire.request(
    url,
    method: .get,
    headers: headers_employees).responseJSON {
        response in
    // Map via ObjectMapper
    let [User] = Mapper<User>().map(JSONObject:response.result.value)
}

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

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