Chris G.
Chris G.

Reputation: 25934

Alamofire parameter with array in class

This is a recurrent problem for me - can I use SwiftyJSON to do this or how?

How can you get the following JSON via .POST with Alamofire :

{
    "class":"Class of 1969",
        "students": 
        [
            {
                "name":"A name",
                "age":25
            },
            {
                "name": "B name",
                "age": 25
            }
        ]
}

I have the following class:

import UIKit

import SwiftyJSON

class Student{
    var Name:String = ""
    var Age: Int = 0
}

class StudentsOf1969{
    var Teacher: String = ""
    var Students = [Student]()
   }


Alamofire

        Alamofire.request(.POST,
            strUrl,
            parameters: parameters, // How?????????
            encoding: .JSON,
            headers: headersWish).responseObject {...


I have tried something like this - adding a var dictionary: [String: AnyObject] to the class:

class Student{
    var Name:String = ""
    var Age: Int = 0
}

class StudentsOf1969{
    var Teacher: String = ""
    var Students = [Student]()

var dictionary: [String: AnyObject]{
    get {
        return [
            "teacher": self.Teacher,
            "students": self.Students,
            // or
            "students": [self.Students],
            ]
    }
}


   }

Upvotes: 1

Views: 305

Answers (1)

Rob
Rob

Reputation: 437392

In addition to giving StudentsOf1969 a dictionary property, you should do the same with Student. And then when you call the description method of StudentsOf1969, it will call the dictionary property for each Student in the array (which can be done quite gracefully with Swift's map function).

For example:

struct Student {
    var name: String
    var age: Int

    var dictionary: [String: AnyObject] {
        get {
            return ["name": name, "age": age]
        }
    }
}

struct ClassOfStudents {
    var className: String
    var students: [Student]

    var dictionary: [String: AnyObject] {
        get {
            return [
                "class": className,
                "students": students.map { $0.dictionary }
            ]
        }
    }
}

Note, I renamed StudentsOf1969 to ClassOfStudents to make it more clear that it's, more generally, used for any class of students, not those in 1969. Also, your JSON referenced class name, not teacher name, so I modified that accordingly.

Anyway, you can now get the parameters dictionary by calling dictionary method of classOf1969:

let classOf1969 = ClassOfStudents(className: "Class of 1969", students: [
    Student(name: "A name", age: 25),
    Student(name: "B name", age: 25)
])

let parameters = classOf1969.dictionary

Upvotes: 1

Related Questions