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 gives 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?
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)!)
}
Here is code to convert between JSON and NSData in swift 2.0 (adapted from Shuo's answer)
// Convert from NSData to json object
func nsdataToJSON(data: NSData) -> AnyObject? {
do {
return try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)
} catch let myJSONError {
print(myJSONError)
}
return nil
}
// Convert from JSON to nsdata
func jsonToNSData(json: AnyObject) -> NSData?{
do {
return try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted)
} catch let myJSONError {
print(myJSONError)
}
return nil;
}
I have no idea on SwiftyJSON. I use following code snippet to convert between json and nsdata
// Convert from NSData to json object
public class func nsdataToJSON(data: NSData) -> AnyObject? {
return NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: nil)
}
// Convert from JSON to nsdata
public class func jsonToNSData(json: AnyObject) -> NSData?{
return NSJSONSerialization.dataWithJSONObject(json, options: .allZeros, error: nil)
}
@Sunil Targe here is the Swift3 version. Hope this helps. (Adapted from Ciprian Rarau's answer)
Convert data to JSON
func dataToJSON(data: Data) -> Any? {
do {
return try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
} catch let myJSONError {
print(myJSONError)
}
return nil
}
Convert from JSON to data
func jsonToData(json: Any) -> Data? {
do {
return try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted)
} catch let myJSONError {
print(myJSONError)
}
return nil;
}
class ViewController: UIViewController {
let requestURL : NSURL = NSURL(string: "http://www.learnswiftonline.com/Samples/subway.json")!
let session = URLSession.shared
override func viewDidLoad() {
super.viewDidLoad()
fetchData()
}
func fetchData()
{
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: requestURL as URL)
let task = session.dataTask(with: urlRequest as URLRequest) { (data, response, error) -> Void in
let httpResponse = response as! HTTPURLResponse
let statusCode = httpResponse.statusCode
if(statusCode == 200)
{
do {
let jsonResponse = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
print(jsonResponse as! NSDictionary)
}
catch let error
{
print(error)
}
}
}
task.resume()
}
}
Swift 4 that works for me:
// Convert from JSON to nsdata
func jsonToNSData(json: AnyObject) -> NSData?{
do {
return try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted) as NSData
} catch let myJSONError {
print(myJSONError)
}
return nil;
}