Swift2 类中带有数组的Alamofire参数

Swift2 类中带有数组的Alamofire参数,swift2,alamofire,swifty-json,Swift2,Alamofire,Swifty Json,这对我来说是一个反复出现的问题——我可以使用SwiftyJSON来做这件事吗?或者如何做 如何通过Alamofire.POST获取以下JSON: { "class":"Class of 1969", "students": [ { "name":"A name", "age":25 }, {

这对我来说是一个反复出现的问题——我可以使用SwiftyJSON来做这件事吗?或者如何做

如何通过Alamofire.POST获取以下JSON:

{
    "class":"Class of 1969",
        "students": 
        [
            {
                "name":"A name",
                "age":25
            },
            {
                "name": "B name",
                "age": 25
            }
        ]
}
我有以下课程:

import UIKit

import SwiftyJSON

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

class StudentsOf1969{
    var Teacher: String = ""
    var Students = [Student]()
   }
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],
            ]
    }
}


   }

阿拉莫菲尔


我尝试过类似的方法-向类添加var
字典:[String:AnyObject]

import UIKit

import SwiftyJSON

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

class StudentsOf1969{
    var Teacher: String = ""
    var Students = [Student]()
   }
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],
            ]
    }
}


   }

除了为1969的
StudentsOf1969
提供一个
dictionary
属性外,您还应该对
Student
执行相同的操作。然后,当您调用1969年
StudentsOf1969
description
方法时,它将为数组中的每个
Student
调用
dictionary
属性(这可以通过Swift的
映射
函数优雅地完成)

例如:

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 }
            ]
        }
    }
}
请注意,我将1969年的
StudentsOf1969
重命名为
ClassOfStudents
,以更清楚地表明,它更普遍地用于任何一个班级的学生,而不是1969年的学生。另外,您的JSON引用了类名,而不是教师名,所以我相应地修改了它

无论如何,您现在可以通过调用
class1969
dictionary
方法来获取
参数
字典:

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

let parameters = classOf1969.dictionary

非常感谢你!!在之前的一次尝试中,我非常想念那本0.5美元的字典。没错!