We often come across a condition where JSON string is to be sent to server. for example parameters like username & password is to be posted as JSON String for validating credentials from server.
Best practice is to create an extension of NSDictionary and add a function with a name of your choice(func jsonString here for now) that will return JSONString as String.
for Swift 2.x
func jsonString()->String?{
    do{
      let jsonData:NSData = try NSJSONSerialization.dataWithJSONObject(self, options: NSJSONWritingOptions.PrettyPrinted)
      let jsonString = String(data: jsonData, encoding: NSUTF8StringEncoding)
      return jsonString
    }
    catch{
      return nil
    }
  }
 
for Swift 3.0
func jsonString()->String?{
    do{
      let jsonData:NSData = try JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions.prettyPrinted) as NSData
      let jsonString = String(data: jsonData as Data, encoding: String.Encoding.utf8)
      return jsonString
    }
    catch{
      return nil
    }
  }
 
                       
                    
0 Comment(s)