Raphael Souza Raphael Souza - 7 months ago 9
Swift Question

How to create a JSON from Dictionary with an array

I have an object "itensList", it has the fields "name", "createdAt" and an array of "itens".

I want to be able to build JSON that looks like this:

{
"name": "List name"
"CreatedAt": "12:12 12/12/2016"
"itens": [
{
"title": "Item title"
"CreatedAt": "12:13 12/12/2016"
"isDone": false
},
{
"title": "Another item title"
"CreatedAt": "12:14 12/12/2016"
"isDone": true
}
]
}


I have tried a few different approaches with no success.

Item Object

class Item: Object {

dynamic var name = ""
dynamic var createdAt = NSDate()
dynamic var isDone = false

}


Item List Object

class ItemList: Object {

dynamic var name = ""
dynamic var createdAt = NSDate()
let itens = List<Item>()
}

Answer

For the example, let's make an object similar to what you must have:

class Iten {
    let title:String
    let createdAt:String
    let isDone:Bool

    init(title: String, createdAt: String, isDone: Bool) {
        self.title = title
        self.createdAt = createdAt
        self.isDone = isDone
    }

}

The trick I suggest is to add a computed value that will return a dictionary:

class Iten {
    let title:String
    let createdAt:String
    let isDone:Bool

    init(title: String, createdAt: String, isDone: Bool) {
        self.title = title
        self.createdAt = createdAt
        self.isDone = isDone
    }

    var toDictionary: [String:AnyObject] {
        return ["title": title, "createdAt": createdAt, "isDone": isDone]
    }
}

Let's use it:

let iten1Dict = Iten(title: "title1", createdAt: "date1", isDone: false).toDictionary
let iten2Dict = Iten(title: "title2", createdAt: "date2", isDone: true).toDictionary

We now make the encapsulating dictionary:

let dict: [String:AnyObject] = ["name": "List name", "createdAt": "dateX", "itens": [iten1Dict, iten2Dict]]

To finish, we encode this dictionary to JSON data then we decode it as a String:

do {
    let jsonData = try NSJSONSerialization.dataWithJSONObject(dict, options: .PrettyPrinted)
    if let jsonString = String(data: jsonData, encoding: NSUTF8StringEncoding) {
        print(jsonString)
    }
} catch let error as NSError {
    print(error)
}

And voilĂ :

{
  "createdAt" : "dateX",
  "itens" : [
    {
      "title" : "title1",
      "createdAt" : "date1",
      "isDone" : false
    },
    {
      "title" : "title2",
      "createdAt" : "date2",
      "isDone" : true
    }
  ],
  "name" : "List name"
}
Comments