Create JSON in swift

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.


Creating a JSON String:

let para:NSMutableDictionary = NSMutableDictionary()
para.setValue("bidder", forKey: "username")
para.setValue("day303", forKey: "password")
para.setValue("authetication", forKey: "action")
let jsonData = try! NSJSONSerialization.dataWithJSONObject(para, options: NSJSONWritingOptions.allZeros)
let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding) as! String
print(jsonString)

One problem is that this code is not of type Dictionary.

let jsonObject: [Any]  = [
    [
         "type_id": singleStructDataOfCar.typeID,
         "model_id": singleStructDataOfCar.modelID, 
         "transfer": savedDataTransfer, 
         "hourly": savedDataHourly, 
         "custom": savedDataReis, 
         "device_type":"iOS"
    ]
]

The above is an Array of AnyObject with a Dictionary of type [String: AnyObject] inside of it.

Try something like this to match the JSON you provided above:

let savedData = ["Something": 1]

let jsonObject: [String: Any] = [ 
    "type_id": 1,
    "model_id": 1,
    "transfer": [
        "startDate": "10/04/2015 12:45",
        "endDate": "10/04/2015 16:00"
    ],
    "custom": savedData
]

let valid = JSONSerialization.isValidJSONObject(jsonObject) // true

Tags:

Object

Json

Swift