Vik Singh
Vik Singh

Reputation: 1603

NSJSONSerialization json data from Swift dictionary containing struct as values

I am trying to convert a swift dictionary (that has String as keys and struct as values) into json data using NSJSONSerialization. But I am getting this error:

Cannot invoke 'dataWithJSONObject' with an argument list of type'([String : Vik.Version], options: NSJSONWritingOptions, error: nil)

Is there anything that I am missing. any help would be appreciated.

Thanks

Following is my code.

final class Vik: NSObject {

    private struct Version {
       private var name: String
       private var filesToAdd = [String]()
       private var filesToRemove = [String]()

       init(name: String, filesToAdd: [String]?, filesToRemove: [String]?) {
          self.name = name

          if let filesToAdd = filesToAdd {
            self.filesToAdd = filesToAdd
          }

          if let filesToRemove = filesToRemove {
            self.filesToRemove = filesToRemove
          }
       }
    }
    ......
    ......
    ......

    private var changeLogDict = [String : Version]()

    private func addToDirectory() {
       .......
       .......
       let jsonData = NSJSONSerialization.dataWithJSONObject(self.changeLogDict, options: NSJSONWritingOptions.PrettyPrinted, error: nil)
       .......
       .......
    }

}

Upvotes: 0

Views: 2329

Answers (1)

Vik Singh
Vik Singh

Reputation: 1603

I figured it out. NSJSONSerialization.dataWithJSON method takes 'AnyObject' data type. Swift dictionary is a struct not an object and hence its complaining. Following line compiles fine

let jsonData = NSJSONSerialization.dataWithJSONObject(self.changeLogDict as NSDictionary, options: NSJSONWritingOptions.PrettyPrinted, error: nil)

Upvotes: 3

Related Questions