0

I'm looking on how to construct or create a son object from a list of class objects.

I have a Category class which look like :

class Category {

    var Code: Int?
    var Label: String?


    init(Code: Int, Label: String) {
        self.Code = Code
        self.Label = Int

    }
}

and then I have a list of category var categories = [Category]()

and then I append my list like this :

  categories.append(5,"Shoes")

How can I construct a json object which will look like this :

{
"List":[
{
"Code":"5",
"Label":"Shoes"
},

....
]
}
Stranger B.
  • 9,004
  • 21
  • 71
  • 108

1 Answers1

1

Step 1

First of all we update your Category class.

class Category {

    var code: Int // this is no longer optional
    var label: String // this neither

    init(code: Int, label: String) {
        self.code = code
        self.label = label
    }

    var asDictionary : [String:AnyObject] {
        return ["Code": code, "Label": label]
    }
}

Step 2

Now we create a list of categories

var categories = [
    Category(code: 0, label: "zero"),
    Category(code: 1, label: "one"),
    Category(code: 2, label: "two")
]

Then we transform them into a list of dictionaries

let list = categories.map { $0.asDictionary }

And finally let's create the json

let json = ["List":list]

That looks valid

NSJSONSerialization.isValidJSONObject(json) // true

Hope this helps.

Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
  • But how to convert it to JSON, the variable JSON is still a list – Stranger B. Aug 07 '15 at 19:04
  • No the variable `json` is a dictionary [String:AnyObject] and it does represent a JSON. What type of object did you expect? – Luca Angeletti Aug 07 '15 at 19:09
  • I want a json object that I can send within a post request – Stranger B. Aug 09 '15 at 10:52
  • You can transform the Dictionary to NSData with NSJSONSerialization.JSONObjectWithData as described here http://stackoverflow.com/questions/27654550/how-to-create-and-send-the-json-data-to-server-using-swift-language. Then you can perform a POST request. – Luca Angeletti Aug 09 '15 at 12:05