I need to create JSON like this:
Order = { type_id:\'1\',model_id:\'1\',
transfer:{
startDate:\'10/04/2015 12:45\',
endDate:\'10/04/2015 16:0
For Swift 3.0, as of December 2016, this is how it worked for me:
let jsonObject: NSMutableDictionary = NSMutableDictionary()
jsonObject.setValue(value1, forKey: "b")
jsonObject.setValue(value2, forKey: "p")
jsonObject.setValue(value3, forKey: "o")
jsonObject.setValue(value4, forKey: "s")
jsonObject.setValue(value5, forKey: "r")
let jsonData: NSData
do {
jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: JSONSerialization.WritingOptions()) as NSData
let jsonString = NSString(data: jsonData as Data, encoding: String.Encoding.utf8.rawValue) as! String
print("json string = \(jsonString)")
} catch _ {
print ("JSON Failure")
}
EDIT 2018: I now use SwiftyJSON library to save time and make my development life easier and better. Dealing with JSON natively in Swift is an unnecessary headache and pain, plus wastes too much time, and creates code which is hard to read and write, and hence prone to lots of errors.