Raphael Souza
Raphael Souza

Reputation: 541

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>()
}

Upvotes: 1

Views: 106

Answers (3)

Eric Aya
Eric Aya

Reputation: 70119

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"
}

Upvotes: 1

pacification
pacification

Reputation: 6018

Like this:

var item = [
    "title": "Item title",
    "CreatedAt": "12:13 12/12/2016",
    "isDone": false
]

var mainDictionary = [
    "name": "List name",
    "CreatedAt": "12:12 12/12/2016",
    "items": [item]
]

And the just convert to json with NSJSONSerialization like this:

do {
    let json = try NSJSONSerialization.dataWithJSONObject(mainDictionary, options: [])
} catch {
    print(error)
}

UPDATE:

If you need to add values to array in dictionary you can do that like this:

if var items = mainDictionary["items"] as? NSMutableArray {
    items.addObject(newItem)
    mainDictionary["items"] = items
}

Upvotes: 0

user3069232
user3069232

Reputation: 8995

Raphael,

This piece of code builds a JSON query. It should get you started, just keep hacking and you'll find a way! That's the fun of programming!

func JSONquery() 
 let request = NSMutableURLRequest(URL: NSURL(string:        "https://api.dropboxapi.com/2/files/get_metadata")!)
    let session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"

    request.addValue("application/json",forHTTPHeaderField: "Content-Type")
    request.addValue("path", forHTTPHeaderField: lePath)
    let cursor:NSDictionary? = ["path":lePath]
    do {
        let jsonData = try NSJSONSerialization.dataWithJSONObject(cursor!, options: [])
        request.HTTPBody = jsonData
        print("json ",jsonData)
    } catch {
        print("snafoo alert")
    }

        let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
        if let error = error {
            completion(string: nil, error: error)
            return
        }
        let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
        //print("Body: \(strData)\n\n")
        do {
            let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers);
            self.jsonPParser(jsonResult,field2file: "ignore")
            /*for (key, value) in self.parsedJson {
                print("key2 \(key) value2 \(value)")
            }*/

            completion(string: "", error: nil)
        } catch {
            completion(string: nil, error: error)
        }
    })
    task.resume()

}

Upvotes: 0

Related Questions