Alamofire JSON .GET编码到数组

时间:2018-12-21 16:27:45

标签: swift alamofire

我正在从Web服务获取Web内容。我有这样的数组

"dc:creator": [ "Emre Degirmenci"]

我想在Alamofire中显示在label.text中。我收到此错误

"Cast from 'JSON' to unrelated type '[String : Any]' always fails". 

我使用了[String:Any],但没有成功。

这是我的NSObject对象

var webCreaterName: [String:Any] = [:]

这是我的Web服务代码

func getWebContentsCompleted(){

    var contents: [WebContents] = []
    let headers = [
        "Authorization": "\(self.defaults.object(forKey: "AccessToken")!)",
        "Content-Type": "application/json"
    ]

    Alamofire.request(APIURL.GetWebContents.rawValue, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
       // debugPrint("response: \(response)")

        let httpCode = response.response!.statusCode

        switch response.result {
        case .success(let value):
          let json = JSON(value)

        switch httpCode {
        case 200:

if let webContentDcCretorName = data[i]["dc:creator"] as? [String:Any] {
                    content.webCreaterName = webContentDcCretorName
                }

1 个答案:

答案 0 :(得分:0)

dc:creator的值是一个数组,因此您必须声明

var webCreaterName = [String]()

很明显,您正在使用SwiftyJSON。要从JSON获取Swift数组,请使用arrayObject

if let webContentDcCretorName = data[i]["dc:creator"].arrayObject as? [String] {
   content.webCreaterName = webContentDcCretorName
}