Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Dictionary to JSON String

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.84k
    Comment on it

    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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: