1

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>()
}
2
  • I couldn't even make it compile, I didn't think it was relevant. I couldn't nest the array inside the Dictionary... Commented Apr 22, 2016 at 17:37
  • I thought it was understandable the way I asked, sorry. I'm gonna edit it. Commented Apr 22, 2016 at 17:53

3 Answers 3

1

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"
}
Sign up to request clarification or add additional context in comments.

1 Comment

That solved my problem! I just added a little loop through the items and added them as dictionaries to a NSMutableArray and set as "items" in your code. Thanks very much!
0

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

}

1 Comment

it's bad practice to force unwrap data that can be nil. try NSJSONSerialization.dataWithJSONObject(cursor!, options: []). If in this case cursor will be nil, you app will be crash with error. You should use if let ... = ... as? SomeObject to check cursor.
0

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
}

2 Comments

That's useful but I still can't add multiples itens with this. Is there any way where I can append new itens? like mainDictionary["items"].append(newItemDictionary)
@RaphaelSouza, i update my answer for your question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.