Parse JSON - Alamofire



我正在尝试消耗REST Web服务...

我的JSON响应结构是:

"page": 1,
  "results": [
    {
      "poster_path": "/9Hj2bqi955SvTa5zj7uZs6sic29.jpg",
      "adult": false,
      "overview": "",
      "release_date": "2015-03-15",
      "genre_ids": [
        99
      ],
      "id": 441580,
      "original_title": "The Jinx: The Life and Deaths of Robert Durst Season 1 Chapter 6: What the Hell Did I Do?",
      "original_language": "en",
      "title": "The Jinx: The Life and Deaths of Robert Durst Season 1 Chapter 6: What the Hell Did I Do?",
      "backdrop_path": "/3br0Rt90AkaqiwVBZVvVUYD1juQ.jpg",
      "popularity": 1,
      "vote_count": 1,
      "video": false,
      "vote_average": 10
    }
],
  "total_results": 307211,
  "total_pages": 15361
}

我正在尝试获取页面和一系列结果...但是Page(PaginationCount(和结果(JSONARRAY(变量在解析后为零。

有我的代码:

 Alamofire.request(ConstantHelper.kUrlDiscoverMovies, method: .get, parameters: ["api_key": ConstantHelper.kApiKey, "certification" : average, "sort_by" : "vote_average.desc" ]).validate()
            .responseJSON { response in
                switch response.result {
                case .success:
                    if let repoJSON = response.result.value as? JSON {
                        let jsonArray = repoJSON["results"] as? NSMutableArray
                        for item in jsonArray! {
                            guard let movie = Movie(json: item as! JSON) else
                            {
                                print("Issue deserializing model")
                                return
                            }
                            listMovies.append(movie)
                        }
                        if let paginationCount = repoJSON["total_pages"] as? String {
                            completion(listMovies, Int(paginationCount)!, nil)
                        }
                        else {
                            completion(listMovies, 0, nil)
                        }
                    }
                    break
                case .failure(let error):
                    completion(nil, 0, error as NSError?)
                    break
                }
        }

我不知道哪种类型JSON

但是键results的值是[[String:Any]]从不 NSMutableArray

let jsonArray = repoJSON["results"] as? [[String:Any]]

密钥total_pages的值是Int不是String(没有双引号(

if let paginationCount = repoJSON["total_pages"] as? Int {
    completion(listMovies, paginationCount, nil)
}

您可以使用某些本机Swift方法轻松解析JSON(无需使用AlarmOfire(,您只需使用该函数,如果您有帖子请求,请使用某些POST参数。p> ps:a仅是标签值列表,在大多数情况下,标签是字符串,该值可以是类型AnyObject,甚至是列表或字典。为此,您需要调整从服务器中获得的数据,以适应您初始化的变量。

func parseMyJSon(_ username: String, password: String) {
    var request = URLRequest(url: URL(string: "https://myurlHere")!) // if you have a http please enable the http connection
    request.httpMethod = "POST" // if you have a get request just change it to get 
    // the post parameters
    let postString = "user_name=(username)&password=(password)"
    // Get the request :(get the json)
    request.httpBody = postString.data(using: String.Encoding.utf8)
    let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
        guard error == nil && data != nil else {
            print("error=(error)")
            // Do something
            return
        }
        print("the data we have got from the server : (data!)")
        // Do Something 
        // think about casting your data to NSDictionnary<String,anyObject> in your case or NSDictionnary<String,[String]> // if your values contains a list of Strings 
    })
    task.resume()
}

最新更新