0

Response String : {"status":"failure","message":"link_inactive"}

I would like the same format with NsmutableDictionary or NSDictionary so I can access via key value.

mfitzp
  • 15,275
  • 7
  • 50
  • 70
Akshay Degada
  • 139
  • 2
  • 13
  • convert response string to NSData & then convert NSData to NSDictionary using NSJSonSerialization. – Saurabh Prajapati May 24 '16 at 13:09
  • Welcome to Stackoverflow. Please make sure that you have read "how to ask a good question". Following these guidelines will make it easier for others to answer, and the responses you get will be better and show up quicker. Details are described here: http://stackoverflow.com/help/how-to-ask – tfv May 24 '16 at 13:09

3 Answers3

1

you can do this by JSONObjectWithData method of NSJSONSerialization.

 do {
    let jsonDict: NSDictionary? = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0)) as? NSDictionary
    if let jsonDict = jsonDict {
    print(jsonDict["message"])  

  } catch let error as NSError {
    // error handling
    debugLog(error)
  }
Sahil
  • 9,096
  • 3
  • 25
  • 29
1

Use this code it will help you

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("error")
        }
    }
    return nil
}
0

as Eric D said the original code:

https://stackoverflow.com/a/33173192/846780

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"]
Community
  • 1
  • 1
Klevison
  • 3,342
  • 2
  • 19
  • 32
  • 1
    Klevison i have try many code but i'm new in swift so i'm not exactly solution.! you give me proper solution with well manner , Thanks – Akshay Degada May 24 '16 at 13:13
  • The least you could do when you "borrow" someone else's code is to give attribution. This method is copied from http://stackoverflow.com/a/33173192/2227743 – Eric Aya May 24 '16 at 13:44