Akshay Degada Akshay Degada - 6 months ago 31
Swift Question

How to Convert Response String to NSMutableDictionary in Swift

Response String :
{"status":"failure","message":"link_inactive"} i need same format with NsmutableDictionary or NSDictionary so i'm access via key value, Pleae help any budy i'm new in Swift.

Answer

Try it:

func convertStringToDictionary(text: String) -> [String:AnyObject]? {
    if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
        do {
            let json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as? [String:AnyObject]
            return json
        } catch {
            print("Something went wrong")
        }
    }
    return nil
}

let string =  "{\"status\":\"failure\",\"message\":\"link_inactive\"}"

let dict = convertStringToDictionary(string) //["status": "failure", "message": "link_inactive"]
Comments