解析JSON - Alamofire

时间:2017-04-19 12:36:42

标签: swift alamofire

我正在尝试使用Rest WebService ...

我的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和结果​​数组......但是parse后,page(paginationCount)和结果(jsonArray)变量为nil。

我的代码是:

 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
                }
        }

2 个答案:

答案 0 :(得分:3)

我不知道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)
}

答案 1 :(得分:0)

你可以使用一些原生的Swift方法轻松解析json(不需要使用alarmofire),你可以使用该函数,如果你有一个帖子请求,使用一些帖子参数。

PS:just是一个标签值列表,在大多数情况下,标签是一个字符串,值可以是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()
}