Convert an array to json from swift


I need to convert an array of strings that I get from an xml, into a json file and then save it in a sqlite database.

I have this code:

do {
   let jsonData = try NSJSONSerialization.dataWithJSONObject(dictionaryOrArray, options: NSJSONWritingOptions.PrettyPrinted)
} catch let error as NSError{

But I get this error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write'

The array I believe in the parser xml:

func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
    if elementName == "title" {
        let title: String = foundCharacters.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
        self.currentlyConstructingArticle.titulo = title
    else if elementName == "img" {
        let imgString:String = foundCharacters.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
        self.currentlyConstructingArticle.imagen = imgString
    else if elementName == "description" {
        let descripcion: String = foundCharacters.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
        self.currentlyConstructingArticle.descripcion = descripcion
    else if elementName == "item" {

    self.foundCharacters = ""
asked by 12.08.2016 в 11:23

2 answers


For swift 3:

Given an x array of strings

let stringArray = [ "string1", "string2" ]

You create the JSON from the array

let jsonData = try stringArray, options: .prettyPrinted)

If you want to check, convert the JSON back to string

let string = String(data: jsonData, encoding: .utf8) 

If you have a problem it's with the strings array you're trying

answered by 17.04.2017 в 22:09
let array = [ "one", "two" ]
let data = NSJSONSerialization.dataWithJSONObject(array, options: nil, error: nil)
let string = NSString(data: data!, encoding: NSUTF8StringEncoding)
answered by 23.08.2016 в 14:26