Alamofire in Swift: converting response data in usable JSON dictionary

ε祈祈猫儿з 提交于 2020-01-04 14:01:23

问题


I would like to handle a JSON string that is returned as data from a HTTP call made using Alamofire.

This question uses SwiftyJSON.

However I wanted to go a little bit "lower level" and understand how to convert the response object into a dictionary.

Reasoning is that it feels that a dictionary may be a simple / easy way to access to the JSON values in the response (rather than having to go through the process of converting the response to a JSON object).

This is under the assumption that JSON objects and dictionaries are the same thing (are they?).

Here is the sample function that I wrote:

func question() -> Void{
    let response : DataRequest = Alamofire.request("http://aapiurl", parameters: nil)

    // Working with JSON Apple developer guide:
    // https://developer.apple.com/swift/blog/?id=37

    response.responseJSON { response in
        if let JSON  = response.result.value
        {

            print("JSON: \(JSON)") // Works!

            let data  = JSON as! NSMutableDictionary
            // Casting fails
            // Could not cast value of type '__NSCFArray' (0x19f952150) to 'NSMutableDictionary' (0x19f9523f8).
            print("Data: \(data)")
        }
    }
}

EDIT:

The JSON object seems to be of type Any and does not have any of the methods that are suggested in the answers below.

I have tried to convert it to a Dictionary and got the error below:


回答1:


A JSON object IS a Dictionary (or possibly an Array at top level).

Note that you should not be using NSMutableDictionary or NSDictionary (or NSArray or NSMutableArray) in Swift.

Also, JSON objects are not working objects. JSON is a way to move data around. It is not to be used as a data source.

If you want to edit the information you get from JSON then you should construct proper data objects from that JSON and work with them.

If you then need to send JSON from this new data then you take your data objects and convert them back to dictionaries and arrays (i.e. JSON objects) and send that data.




回答2:


Alamofire has the result value of type Any because it usually would be an array or a dictionary. In Swift you normally shouldn't use NS* classes, but rather native swift types such as Array and Dictionary.

You can (should) use optionals to look into the returned JSON object:

if let array = response.result.value as? [Any] {
    print("Got an array with \(array.count) objects")
}
else if let dictionary = response.result.value as? [AnyHashable: Any] {
    print("Got a dictionary: \(dictionary)")
}
...

Depending on what you expect from your backend, you can treat each of the cases as a success or a failure.




回答3:


    Alamofire.request(myUrl)
        .responseJSON  {
            response in

            if let dict = response.result.value as? [String : Any] {

               debugPrint(dict)

               wishLists.removeAll()  //[[String:Any]]

               let lists = dict["wishlists"] as! [String: Any]

               debugPrint(lists)

               for (key, value) in lists {

                   var list = value as! [String: Any]

                    wishLists.append(list)

                }

                debugPrint(wishLists)

                self.tableView.reloadData()

            }

    }


来源:https://stackoverflow.com/questions/41613683/alamofire-in-swift-converting-response-data-in-usable-json-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!