简体   繁体   English

解析JSON-Alamofire

[英]Parse JSON - Alamofire

I'm trying to consume a Rest WebService... 我正在尝试使用Rest WebService ...

My JSON response structure is: 我的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
}

I'm trying to get Page and Array of results...but page(paginationCount) and results(jsonArray) variable are nil after parse. 我正在尝试获取结果的页面和数组...但是解析后的page(paginationCount)和results(jsonArray)变量为nil。

There's my code: 有我的代码:

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

I don't know what type JSON is, 我不知道JSON是什么类型,

but the value for key results is [[String:Any]] , never NSMutableArray 但是关键results的值是[[String:Any]]从不 NSMutableArray

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

and the value for key total_pages is Int not String (there are no double quotes) 并且键total_pages的值是Int而不是String (没有双引号)

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

You can easily parse json using some native Swift method( no need to use alarmofire ) , you can just use the function , if you have a post request , using some post parameters. 您可以使用某些本机Swift方法轻松地解析json(无需使用Alarmofire),如果有发布请求,则可以使用一些post参数来使用该函数。

PS : a just is a list of tag value , the tag is a String in most cases and the value could be of type anyObject or even a list or a dictionary. PS:just是标签值的列表,在大多数情况下标签是String,值的类型可以是anyObject甚至列表或字典。 For that you need to adapt the data you get from the server to the variables that you have initialised. 为此,您需要使从服务器获取的数据适应已初始化的变量。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM