John Smith John Smith - 1 year ago 131
Swift Question

Converting JSON to NSData, and NSData to JSON in Swift

I'm having problems converting a JSON element into NSData, and an NSData variable back into JSON in Swift.

Firstly, I'd like to extract the 'encryptedData' element of the following JSON data:

"transactionID" : 12345,
"encryptedData" : [-67,51,-38,61,-72,102,48]

into an NSData 'encryptedData' variable but can't seem to be able to do it. I'm using SwiftyJSON to parse the JSON as follows:

let list: Array<JSON> = json["encryptedData"].arrayValue!

But this give me an array of ScalarNumber which I don't know how to store into an NSData object.

Secondly, I'd like to generate JSON back from the same NSData object:

let jsonObject = [
"transactionID" : 12345,
"encryptedData" : encryptedData

But the NSData 'encryptedData' object doesn't get converted into [-67,51,-38,61,-72,102,48], it just seems to nullify the JSON string.

Any ideas?


Answer Source

In SwiftyJSON you can use rawData method to get NSData:

if let encryptedData:NSData = json["encryptedData"].rawData() {
    NSLog(NSString(data: encryptedData, encoding: NSUTF8StringEncoding)!)

To generate JSON as you want you should convert data to array object:

if let encryptedDataArray = JSON(data: encryptedData).arrayObject {
    let jsonObject:JSON = [
        "transactionID" : 12345,
        "encryptedData" : encryptedDataArray
    NSLog(NSString(data: jsonObject.rawData()!, encoding: NSUTF8StringEncoding)!)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download