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

....
]
}
2

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

But how to convert it to JSON, the variable JSON is still a list
No the variable json is a dictionary [String:AnyObject] and it does represent a JSON. What type of object did you expect?
I want a json object that I can send within a post request
You can transform the Dictionary to NSData with NSJSONSerialization.JSONObjectWithData as described here stackoverflow.com/questions/27654550/…. Then you can perform a POST request.

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.