Search code examples
jsonswiftalamofire

From Swift object to json (formated [String: Any]) for alamofire REST post parameter (defined as [String: Any])


My purpose is to execute a REST post request via Alamofire.

I have an object:

struct Dog: Codable {
    var name: String
    var owner: String
}

I use this :

let JSONString = user.toJSONString(prettyPrint: true) //ObjectMapper call 

returning :

{
    "name" : "Jon",
    "owner" : "Jon Doe"
}

But I want a [String: Any] structure, suitable for alamofire request like :

[
    "name" : "Jon",
    "owner" : "Jon Doe"
]

How to do that ?


Solution

  • Your Dog is not correctly configured to use ObjectMapper, missing Mappable protocol.

    struct Dog: Mappable  {
        var name: String?
        var owner: String?
    
        init?(map: Map) {
    
        }
    
        // Mappable
        mutating func mapping(map: Map) {
            name    <- map["name"]
            owner   <- map["owner"]
        }
    }
    

    Then you can use BaseMappable.toJSON to pass to Alamofire's parameter, which is [String: Any]

    let parameters: Parameters = user.toJSON()
    _ = Alamofire.request(theURL, method:.post, parameters: parameters, encoding: JSONEncoding.default).validate().responseJSON() {
        // -----...
    }
    

    PS: Your user mustn't be a Dog I guess? :P