1

假设我得到了以下结构

public class Response: Codable {
    let status: String
    let code: String
    let id: String
}

我想要的是获取类属性和值,[String: Any]以便像这样通过 Alamofire 发送它:

let response: Response = Response(status: "A", code: "B", uuid: "C")
let data = try JSONEncoder().encode(res)

//Data to [String : Any]

Alamofire.request("endpoint", method: .post, parameters: params).responseJSON {
    // Handle response
}
4

2 回答 2

1

你可以使用这样的东西:

let response: Response = Response(status: "A", code: "B", uuid: "C")
let data = try JSONEncoder().encode(res)

//Data to [String : Any]
do {
    let params = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any]
    Alamofire.request("endpoint", method: .post, parameters: params).responseJSON {
        // Handle response
    }
} catch {
    print(error)
}
于 2018-01-09T05:03:12.910 回答
-1

Try using JSONSerialization as below I had used to get data from JSON

func HitApi(){
    Alamofire.request(urlToGetTimeTable, method: .get, parameters: nil , encoding:URLEncoding.default).responseJSON { (response) in

        if(response.result.isSuccess)
        {
            if let JSON = response.result.value
            {
                print("JSON: \(JSON)")
                do {
                        //Clearing values in Array
                        self.subjectNameArray.removeAll()
                        //get data and serialise here to get [String:Any]
                        if let data = response.data,
                            let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
                            let dataDict = json["data"] as? [[String: Any]]

                        {
                            // iterate an array
                            for dict in dataDict
                            {
                                //get data from JSON Response
                                let subjectName = dict["subjects_id"] as? String
                                self.subjectNameArray.append(subjectName!)
                            }
                            // TableView Delegate & DataSource
                            // Reload TableView
                            self.tableView.dataSource = self;
                            self.tableView.delegate = self;
                            self.tableView.reloadData()

                        }

                }
                catch
                {
                    //Error case
                    print("Error deserializing JSON: \(error)")

                }

            }
        }

        if(response.result.isFailure)
        {
            //Show Alert here //reason Failure
        }


    }
}

Give you an idea to get response as [String:Any] using son serialisation , you can use Above format in Post Method need some Modification. I deleted Rest code and showed main Code that was required

于 2018-01-09T05:02:01.487 回答