我正在用Swift接收下面的JSON文件,我不知道如何获取JSON中的details元素

[
  {
    "id": 143369,
    "history": "jd2",
    "details": [
      {
        "name": "Su 1",
        "color": "#ffffff"
      },
      {
        "name": "Stu 1",
        "color": "#ffffff"
      }
    ]
  },
  {
    "id": 143369,
    "history": "musa 2",
    "details": [
      {
        "name": "Stu 1",
        "color": "#ffffff"
      },
      {
        "name": "Stu 2",
        "color": "#ffffff"
      }
    ]
  }
]

我已经创建了这个类,使用它我可以检索id和历史记录,但不能检索细节。如何将详细信息包括在id和历史记录中?
public class students {

    let id: Int32
    let history: String?

    init(id:Int32, history:String) {
        self.id = id
        self.history = name

    }
}

下面是我的web服务代码。
var dataArray = [students]()

    Alamofire.request(.GET, url)
        .responseJSON { response in

            if let value: AnyObject = response.result.value {

                let json = JSON(value)
                if let items = json.array {
                    for item in items {
                           self.dataArray.append(students(
                            id: item["id"].int32!,
                            history: item["history"].string!))

                            let cItems = item["details"].array
                                for citem in citems {
                                    //here
                                }
                    }
                }
            }
    }

最佳答案

你的学生模型应该是这样的。

let id: Int32
let history: String?
let details: Array<[String:AnyObject]>
init(id:Int32, history:String,details:Array<[String:AnyObject]>) {
    self.id = id
    self.history = name
    self.details= details //need a cast here!
}

下面是一个简单的解析器,我在一个项目中使用它来转换数组
func collection(data:[[String:AnyObject]]) -> [yourModel] {

        var objectArray: [yourModel] = []

        for d in data {

            let obj = yourModel(data: d as [String: AnyObject]) // i created a initializer for this object here on my project.

            objectArray.append(obj)

        }

        return objectArray

}

希望能给你一个主意!

关于json - 快速获取JSON元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41243925/

10-14 16:21
查看更多