Search code examples
iosjsonswiftnsdictionarynsjsonserialization

How to generate JSON data from NSDictionary in Swift


I'm new to Swift and I am trying to generate JSON data from an NSDictionary

Here's my code:

func metricsToJson() {
        if let data = NSJSONSerialization.dataWithJSONObject(metricsData, options: NSJSONWritingOptions.PrettyPrinted, error: &error) {
            if let json = NSString(data: data, encoding: NSUTF8StringEncoding) {
                println(json)
            }

        }
    }

enter image description here I'm not sure why this isn't working, but any guidance would be greatly appreciated.


Solution

  • Try below code, it may help to solve your problem.

    var jsonResult = NSJSONSerialization.JSONObjectWithData(metricsData, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSArray
    
    for var i = 0; i<jsonResult.count; ++i {
    
        var dictResult = jsonResult.objectAtIndex(i) as! NSDictionary
        // your code...
    }